开发者

PHP duplicated list

开发者 https://www.devze.com 2023-03-18 19:20 出处:网络
Here is my code to list all category as a list item: if ($xml) { foreach($xml->children() as $IRXML) {// SHOW ONLY 5 NEWS ITEMS

Here is my code to list all category as a list item:

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> ";
                }
            }

    开发者_如何学Python    }
    }

}

What I wanted to do is only to display a category without duplicating it.


$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;
                }
            }
        }
    }
}

Check out the in_array function from the documentation.


Do you mean you want to display each one only once? If .children() is returning the same child twice, that could be another problem; if it's not something you can change and this is the behavior you're seeing, you could keep an array of category names/ID's, append as you display them, and check the array for duplicates before writing output each time the loop runs.


Assuming there is no way to eliminate the duplicates when generating the XML...that would be more efficient.

You could create an array outside of the loop, and then check to see if a category has already been seen. Example:

$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> ";
    }
} 
0

精彩评论

暂无评论...
验证码 换一张
取 消