PHP重复列表

时间:2011-07-08 15:05:31

标签: php simplexml

以下是我将所有类别列为列表项的代码:

if ($xml) {
    foreach($xml->children() as $IRXML) {                                                                           // SHOW ONLY 5 NEWS ITEMS

        foreach($IRXML->children() as $newsrelease) {                                               // EACH NEWSRELEASE IS ONE SUBCHILD

            // echo "   <div class='news-image'>";
            // echo "<img src='/wp-content/themes/bby/images/news-story-01.jpg' alt=''>";
            // echo "</div>";

            $categories = $newsrelease->Categories;
            foreach($categories->children() as $category) {
                if ($category != "NA") {
                    echo "<li class='category ".$category."'>".$category."</li> ";
                }
            }

        }
    }

}

我想要做的只是显示一个类别而不重复它。

3 个答案:

答案 0 :(得分:0)

你的意思是你想只展示一次吗?如果.children()两次返回同一个孩子,那可能是另一个问题;如果它不是你可以改变的东西,这是你所看到的行为,你可以保留一个类别名称/ ID的数组,在显示它们时附加,并在每次循环运行时在写入输出之前检查数组是否有重复。 / p>

答案 1 :(得分:0)

假设在生成XML时没有办法消除重复...那会更有效率。

您可以在循环外部创建一个数组,然后检查是否已经看到某个类别。例如:

$categories = $newsrelease->Categories;
$seen_categories = array();
foreach($categories->children() as $category) {
    if ($category != "NA" && !in_array($category,$seen_categories)) {
        $seen_categories[]=$category;
        echo "<li class='category ".$category."'>".$category."</li> ";
    }
} 

答案 2 :(得分:0)

$list_cache = array();

if ($xml)
{
    foreach($xml->children() as $IRXML) 

    foreach($IRXML->children() as $newsrelease) 
    {

        $categories = $newsrelease->Categories;

        foreach($categories->children() as $category)
        {
            if ($category != "NA")
            {
                $print_category = "<li class='category ".$category."'>".$category."</li> ";

                if( !in_array($print_category, $list_cache) )    //check if you've stored in previously in this array. In such case, in_array will return true. 
                {
                    $list_cache[] = $print_category;
                    echo $print_category;
                }
            }
        }
    }
}

从文档中查看in_array功能。