2017-06-07 50 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