PHP: Foreach in a multidimensional array [duplicate]

≡放荡痞女 提交于 2021-01-28 05:23:18

问题


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>";
}

?>

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.

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


回答1:


change your loop as

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



回答2:


You were not far off:

<?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']);

Output:

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

To target an individual value from $cars using keys:

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

Output:

BMW



回答3:


You may do something like this

<?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);
?>


来源:https://stackoverflow.com/questions/46322612/php-foreach-in-a-multidimensional-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!