2017-06-07 87 views
0

我有一個打印新聞稿的XML文件。我想回顧新聞稿發佈之前的所有年份,如檔案。唯一的價值。下面的代碼打印出所有年份。像「2017,2017,2017,2016,2016,2015,2015,2014」以外的「2017,2016,2015,2014,2013」​​。回聲只有唯一值

<?php 
$file = "file.xml"; 
$xml = simplexml_load_file($file); 

foreach ($xml->Release as $release) { 
    $date = $release['PublishDateUtc']; /* $date is now in format yyyy-mm-ddT06:30:00 */ 
    $year = substr($date, 0, 4); 
    echo $year; 
} 

?> 
+0

值是否總是按順序?然後將最後一個值存儲在變量中,並且只在最後一個值不等於當前值時纔回顯。 –

回答

2

記下已打印的日期。

$printed = []; 

foreach ($xml->Releases as $release) { 
    $year = date('Y', strtotime($release['PublishDateUtc'])); 

    if (!isset($printed[$year])) { 
     echo $year; 
     $printed[$year] = $year; 
    } 
} 
+0

你可以做'echo $ printed [$ year] = $ year',保存一行代碼。 – Xorifelse

+0

@Xorifelse對我來說,它不是很可讀。 – Justinas

+0

謝謝,這對我幫助很大! – hogan

0

嘗試這個

<?php 
$file  = "file.xml"; 
$xml   = simplexml_load_file($file); 
$yearArray = array(); 
$uniqueArray = array(); 
foreach ($xml->Release as $release) { 
    $date  = $release['PublishDateUtc']; 
    /* $date is now in format yyyy-mm-ddT06:30:00 */ 
    $year  = substr($date, 0, 4); 
    $yearArray[] = $year; 
} 

$uniqueArray = array_unique($yearArray); 
print_r($uniqueArray); 
?> 

初始化2個額外的變數,使多年陣列內loop.then印刷獨特的陣列。

+0

謝謝,這工作得很好! – hogan