如何遍历PHP中的此键控多维数组?

时间:2019-01-25 13:19:25

标签: php arrays

我有以下数组:

<?php
$cars = array(
            "cars" => array
                (
                    array("make" => "Volvo", "model" => "2018", "price" => 31.91),
                    array("make" => "BMW", "model" => "2015", "price" => 34.50),
                    array("make" => "Toyota", "model" => "2019", "price" => 27.58)
                )
            );

echo "<pre>";
print_r($cars);
echo "</pre>";
?>

人类可读形式:

Array
(
    [cars] => Array
        (
            [0] => Array
                (
                    [make] => Volvo
                    [model] => 2018
                    [price] => 31.91
                )

            [1] => Array
                (
                    [make] => BMW
                    [model] => 2015
                    [price] => 34.5
                )

            [2] => Array
                (
                    [make] => Toyota
                    [model] => 2019
                    [price] => 27.58
                )

        )

)

我们如何遍历此数组以获取每个元素?是否有必要使用OUTER foreach循环来获取cars数组内部的访问权限?如果我们已经提前知道密钥,我们是否可以不直接访问它们?

我正在使用以下方法:

<?php
foreach($cars as $key => $array)
{
    echo "Key: " . $key;
    echo "<hr />";
    foreach($array as $sub_key => $sub_array)
    {
        echo "Make:" . $sub_array['make'];
        echo "<br />";
        echo "Model:" . $sub_array['model'];
        echo "<br />";
        echo "Price:" . $sub_array['price'];
        echo "<hr />";
    }
}
?>

输出:

Key: cars

Make:Volvo
Model:2018
Price:31.91

Make:BMW
Model:2015
Price:34.5

Make:Toyota
Model:2019
Price:27.58

如何在不使用外部foreach循环的情况下遍历数组元素?我的意思是不使用

foreach($cars as $key => $array)

编辑

我认为这绝不是这些问题的重复。我的问题是避免需要外循环而不是内循环。

0 个答案:

没有答案