PHP:Foreach在一个多维数组中

时间:2017-09-20 12:51:22

标签: php arrays multidimensional-array foreach

为学校做了一个多维数组的作业。

<?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。不知道如何解决它。

我知道如何只使用echo来显示它,但我的任务是说我必须使用foreach。我根本没有使用PHP的经验,所以我希望你们能以正确的方式指出我。提前致谢。

3 个答案:

答案 0 :(得分:1)

你离我不远:

<?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($cars as $car)
    printf("%-10s %s\n",  $car['brand'], $car['license']);

输出:

BMW        30-KL-PO
Mercedes   51-ZD-ZD
Maserati   JB-47-02

使用键从$cars定位单个值:

echo $cars['car1']['brand'];

输出:

BMW

答案 1 :(得分:0)

将您的循环更改为

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

答案 2 :(得分:0)

你可能会做这样的事情

<?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
    )
);
$result = []; // blank array to store result 
foreach($cars as $key => $val):
$result[$key]["brand"] = $val["brand"]; 
$result[$key]["license"] = $val["license"]; 
endforeach;
#echo "<pre>";
#print_r($result);
?>