问题
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