php foreach相同的值多次,但只打印一次

时间:2013-02-26 22:18:40

标签: php foreach

我有一个带有节目和季节的xml文件。

我要做的是读出一个节目的季节。但问题是每个季节在同一节目下多次出现。

我只希望每个季节打印一次,如:

Season 1
Season 2

但我现在得到的是:

Season 1
Season 2
Season 2
Season 1
Season 1

我的xml看起来像

<?xml version="1.0"?>
<episodeview>
<episodeview>
    <idShow>1</idShow>
    <idSeason>1</idSeason>
</episodeview>
<episodeview>
    <idShow>1</idShow>
    <idSeason>2</idSeason>
</episodeview>
<episodeview>
    <idShow>1</idShow>
    <idSeason>2</idSeason>
</episodeview>
<episodeview>
    <idShow>1</idShow>
    <idSeason>1</idSeason>
</episodeview>
<episodeview>
    <idShow>1</idShow>
    <idSeason>1</idSeason>
</episodeview>
</episodeview>

我的php文件:

<?php
$idShow = "1";
$source = "show.xml";

$xmlstr = file_get_contents($source);
$xmlcont = new SimpleXMLElement($xmlstr);
foreach($xmlcont as $url) {
    if ($url->idShow == $idShow) {
        $test = $url->idSeason;
        echo "Season ";
        echo $test;
        echo "<br>";
     }      
}

&GT?;

3 个答案:

答案 0 :(得分:3)

试试这个,简短而甜蜜:

 $xml=simplexml_load_file($source); // (1)

 foreach ($xml->xpath("//idSeason") As $season) { // (2)

      $s[(int)$season]=$season; // (3)
 }

 foreach ($s As $a) echo "Season $a<br />"; // (4)
  1. 从文件中获取simplexml - 元素

  2. 仅使用<idSeason>选择xpath - 节点并迭代它们

  3. 使用season-id作为索引和值 - &gt;创建一个新数组$s数组索引必须是唯一的,因此重复的ID不会放大数组,但如果索引已存在则“覆盖”索引。

  4. 遍历$s以回应它

  5. 我知道人们只能通过xpath选择唯一值,但我不熟练;-) 而simplexml不支持xpath 2.0,这更容易。

答案 1 :(得分:1)

尝试:

<?php
$idShow = "1";
$source = "show.xml";
$have = array();

$xmlstr = file_get_contents($source);
$xmlcont = new SimpleXMLElement($xmlstr);
foreach($xmlcont as $url) {
    if ($url->idShow == $idShow) {
        $test = $url->idSeason;
         if( ! in_array( $test, $have) ){ //Check if the season already is displayed
           echo "Season ";
           echo $test;
           echo "<br>";
           $have[] = $test; //Store the season in the array
          }
     }      
}

这样您就可以存储在数组中显示的所有内容,在输出测试之前,它会检查它是否已经显示。

答案 2 :(得分:1)

我会这样做:

<?php
  $idShow = "1";
  $source = "show.xml";

  $xmlstr  = file_get_contents($source);
  $xmlcont = new SimpleXMLElement($xmlstr);
  $seasons = array();
  foreach($xml_cont as $url){ $seasons[] = $url->idSeason; }

  $seasons = array_uniq($seasons);

  foreach($seasons as $season){ echo "Season $season <br />"; } 
?>

当然,我的例子涉及比你可能尝试的其他一些解决方案更多的循环,但我认为它相当有效,也许同样重要,可读。