如何使用键值来处理多维数组

时间:2016-08-02 12:48:05

标签: php arrays multidimensional-array foreach

我有一个带键值的多维数组。我想循环该数组中的数据,但我不知道如何。

这是我的阵列:

$myArray=     Array
    (
        '134' => Array
            (
                '1138' => Array
                    (
                        'id' => 1138,
                        'qty' => 1,
                        'price' => 4900000,
                        'name' => 'Pioneer AVH X5850BT Head Unit Double Din 7Inch',
                        'options' => Array
                            (
                                'image' => '865e6ad631fa45d408acfc6f8a8ff008.jpg',
                                'created_by' => 134
                            ),

                        'rowid' => 'f9e62f7ce9665a25ff40848744dd83f4',
                        'subtotal' => 4900000
                    ),

                '1003' => Array
                    (
                        'id' => 1003,
                        'qty' => 1,
                        'price' => 2250000,
                        'name' => 'Steelmate SW813 Subwoofer Aktif 10 Inch',
                        'options' => Array
                            (
                                'image' => '962df806d5adc7bd0d22666fe996f139.jpg',
                                'created_by' => 134
                            ),

                        'rowid' => '7aa455ef597b2906e3895783bd7a5c70',
                        'subtotal' => 2250000
                    )

            ),

        '157' => Array
            (
                '2527' => Array
                    (
                        'id' => 2527,
                        'qty' => 1,
                        'price' => 2475000,
                        'name' => 'Rockford Fosgate P165SE Speaker Split 2way Komponen',
                        'options' => Array
                            (
                                'image' => '81027273a2ad59a96aec85ec66ce2704.jpg',
                                'created_by' => 157
                            ),

                        'rowid' => 'ed9301accd0d84bd0417609aa80cebc7',
                        'subtotal' => 2475000
                    )

            )

    );

如何循环/ foreach该数组?

我想foreach里面有一个foreach,但我不知道该怎么做。

3 个答案:

答案 0 :(得分:2)

只需在foreach

中使用其他foreach即可
foreach ($myArray as $key => $value) {
    foreach ($value as $subkey => $subvalue) {
        if (is_array($subvalue)) {
            foreach ($subvalue as $subsubkey => $subsubvalue) {
                // .... and so on
            }
        }
    }
}

答案 1 :(得分:2)

您可以在此处使用递归函数,因此您无需担心数组的深度。

这样的事情:

function read($arr) {
    foreach ($arr as $key => $value) {
        if (is_array($value)) {
            read($a);
        }
        else {
            // You cann access key and value here (for each array)
        }
    }
}

read($myArray);

答案 2 :(得分:2)

defaultRingtone.play();