我有一个多维数组
array:2 [▼
"lamborghini" => array:1 [▼
"cars" => array:5 [▼
0 => "1"
1 => "4"
2 => "2"
3 => "5"
4 => "7"
]
]
"ferrari" => array:1 [▼
"cars" => array:1 [▼
0 => "8"
]
]
]
我试图像这样实现可能的输出
Lamborghini
1 4 2 5 7
ferrari
8
我试过这个方法
foreach($cars as $car)
{
foreach($car as $product)
{
for($i=0; $i<count($product); $i++)
{
echo $product[$i];
}
}
}
我实现的输出就是这个
142578
任何人都可以帮助我实现可能的输出吗?它还应该打印第一个数组名称。例如
lamborghini
1 4 2 5 7
答案 0 :(得分:1)
试试这个:
$cars = [
'lamborghini' => [
'cars' => [1, 2, 3, 4],
],
'ferrari' => [
'cars' => [1],
],
];
foreach($cars as $make => $cars) {
echo $make . "<br>";
foreach($cars as $models) {
echo implode(' ', $models) . "<br>";
}
}
我不知道您希望如何显示结果,但您可以删除. <br>
代码。
答案 1 :(得分:0)
你可以改为
<?php
foreach($car as $fer){
foreach($cars as $lamb) {
echo "Lamborghini: ".$lamb;
}
echo "Ferrari: ".$fer;
}
?>
这样它会首先循环羊羔,然后循环法拉利
答案 2 :(得分:0)
这将获得所需的输出:
foreach($car as $car_k => $car)
{
foreach($car as $product => $num_car)
{
echo $car_k. ':' .implode(',',$num_car);
echo "<br/>"
}
}