多维数组中的Foreach

多维数组中的Foreach

本文介绍了PHP:多维数组中的Foreach的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为学校分配了一个多维数组.

Got an assignment for school to make a multidimensional array.

<?php
$cars = array(
        "car1" => array (
            "brand" => 'BMW',
            "license" => '30-KL-PO',
            "price" => 10000
            ),

        "car2" => array (
           "brand" => 'Mercedes',
           "license" => '51-ZD-ZD',
           "price" => 20000
        ),

        "car3" => array (
           "brand" => 'Maserati',
           "license" => 'JB-47-02',
           "price" => 30000
        )
     );

foreach($carss as $car){
echo $car['car1']['brand'] . $car['car1']['brand'] . "<br>";
}

?>

我需要使用foreach展示所有汽车的品牌和许可证.我只用car1尝试过,但出现错误:未定义索引:car1.

I need to show the brand and license of all the cars using a foreach. I tried it with only car1 and I got the error: Undefined index: car1.

我知道如何仅使用echo来显示它,但是我的作业要求我必须使用foreach.

I know how to get it to show using only echo but my assignment says that I have to using a foreach.

推荐答案

将循环更改为

foreach($carss as $key => $car){
   echo $key ." ". $car['brand'] . "<br>";
}

这篇关于PHP:多维数组中的Foreach的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 12:48