简体   繁体   English

PHP 5中的嵌套foreach循环

[英]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. 我有一个数组,其中包含智能手机的制造商名称和一个XML文件,其中包含每个特定电话的规格。

What I am trying to do is to group phones based on manufacturer. 我想做的是根据制造商对电话进行分组。 I am using nested FOREACH loop to do this. 我正在使用嵌套的FOREACH循环来执行此操作。 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示例:

<?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 另外,如果我删除了外循环,代码可以完美运行并显示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. 回声结束时。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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