简体   繁体   中英

nested foreach loop in PHP 5

So here is the deal:

I have an array that contains manufacturers' names for smartphones and an XML file that holds specifications for each specific phone.

What I am trying to do is to group phones based on manufacturer. I am using nested FOREACH loop to do this. And here is my code:

    foreach ($makes as $manufacturer){
        echo '<div>'.'<h2>'.$manufacturer.'</h2>'.'<hr>';
        foreach ($xml as $item){
            if($item->make == $manufacturer){
                $src = $item->thumb;
                echo '<div>'."<img src='$src' width='100'/>".'<h1>'.
                        $item->make.' '.$item->model.'</h1>'.'</div>';
            }
         }  
         echo '</div>';
     }

The problem with this approach is that for some reason my page displays ONLY THE FIRST phone for every manufacturer, instead of going through every model.

What am I doing wrong here?

Here is XML sample:

<?xml version="1.0" encoding="utf-8"?>
<items>
    <item>
       <make></make>
       <model></model>
       <thumb></thumb>
    </item>
</items>

Also, if I remove outer loop, code works perfectly and displays every phone from the XML

You have a typo:

echo '<div>'."<img src='$src' width='100'/>".'<h1>'.
$item->make.' '.$item->model.'</h1>'.

should be

echo '<div>'."<img src='$src' width='100'/>".'<h1>'.
$item->make.' '.$item->model.'</h1>';

Note the ";" at the end of the echo.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM