如何使用嵌套的foreach

时间:2014-07-14 02:03:15

标签: php foreach

我已成功检索汽车品牌和汽车名称,但我不知道如何检索该特定汽车的图像。我尝试使用嵌套的foreach但是没有按照我的预期工作。而不是显示特定的图像汽车ID,它显示所有ID的最后一个文件夹中的相同图像。

这是我的代码:

while($row = mysql_fetch_array($result_name,MYSQL_ASSOC)) {
    $car[$row['carMake_id']][] = $row['carName'];
    //$car_name_id=$row['carName_id'];
    $gallery=$row['gallery'];
    //$car_make_id=$row['carMake_id'];
    //$car_gallery[$row['carName_id']][]=$row['gallery'];
}

foreach ($car as $carmake => $carname) {
    echo "<tr><td style='background-color:#0066cc;'><b>".$carmake ."</b></td></tr><tr>";
    foreach ($carname as $title) {
        echo "<td>".$title . "<br/>&nbsp;";
        ?>
        //this part displays image.. I want it to display according to the car name ($title)
        <img src="management/uploads/<?php echo $carmake;?>/<?php echo $gallery;?>" width="100" height="100"></td>
        <?php
    }
    echo'</tr>';
}

另外,如何在foreach中检索与特定汽车有关的所有其他信息?

感谢。

编辑部分:

$gallery[]=$row['gallery'];//inside while loop


 foreach ($car as $carmake => $carname)
                                        {

                                        echo "<tr><td style='background-color:#0066cc;'><b>".$carmake ."</b></td></tr><tr>";
foreach ($carname as $title) {
echo "<td>".$title . "<br/>&nbsp;";

foreach($gallery as $g)//new foreach to retreive images
{
echo $g;
}
?>

<img src="management/uploads/<?php echo $carmake;?>/<?php echo $g;?>" width="100" height="100"></td>

1 个答案:

答案 0 :(得分:2)

您需要将gallery放入数组中。

<?php 

while($row=mysql_fetch_array($result_name,MYSQL_ASSOC))
    {
        $car[$row['carMake_id']][] = $row;
    }

foreach ($car as $carmake => $carname)
    {
        echo "<tr><td style='background-color:#0066cc;'><b>".$carmake ."</b></td></tr><tr>";
        foreach ($carname as $title)
            {
                echo "<td>{$title['carName']}<br/>&nbsp;";
                //this part displays image.. I want it to display according to the car name ($title)
                echo "<img src='management/uploads/$carmake/{$title['gallery']}' width='100' height='100'></td>";
            }
        echo'</tr>';
    }

?>