如何在PHP中使用foreach循环来执行多维数组?

时间:2017-12-30 15:31:07

标签: php arrays multidimensional-array foreach

我从多维数组中提取数据。使用foreach循环时,我感到困惑,无法从我的数组中提取数据。这是我的数组名为$ result_array:

Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [category_id] => 19
                    [category_name] => Food
                    [publication_status] => 1
                    [deletion_status] => 1
                )

            [1] => Array
                (
                    [category_id] => 16
                    [category_name] => Gourmet
                    [publication_status] => 1
                    [deletion_status] => 1
                )

            [2] => Array
                (
                    [category_id] => 17
                    [category_name] => Islamic Product
                    [publication_status] => 1
                    [deletion_status] => 1
                )


        )

    [1] => Array
        (
            [0] => Array
                (
                    [category_id] => 28
                    [category_name] => Dry Food
                    [publication_status] => 1
                    [deletion_status] => 1
                )

            [1] => Array
                (
                    [category_id] => 39
                    [category_name] => Testt
                    [publication_status] => 1
                    [deletion_status] => 1
                )

            [2] => Array
                (
                    [category_id] => 37
                    [category_name] => Seasonal Items
                    [publication_status] => 1
                    [deletion_status] => 1
                )

            [3] => Array
                (
                    [category_id] => 38
                    [category_name] => Icon Items
                    [publication_status] => 1
                    [deletion_status] => 1
                )

        )

    [2] => Array
        (
            [0] => Array
                (
                    [category_id] => 29
                    [category_name] => Biscuits
                    [publication_status] => 1
                    [deletion_status] => 1
                )

        )

    [3] => Array
        (
            [0] => Array
                (
                    [category_id] => 30
                    [category_name] => Nutty
                    [publication_status] => 1
                    [deletion_status] => 1
                )

        )

)

这是我的循环:

foreach($result_array as $info) {
    echo $info['category_name'].'<br>';
}

这个循环给出了一个错误,说明了未定义的索引category_name。我是这个领域的新手。谁能开导我?感谢

2 个答案:

答案 0 :(得分:4)

你需要双重预告,如下:

foreach($result_array as $outer_array)
    foreach($outer_array as $inner_array)
        echo $inner_array['category_name'] . '<br>';

答案 1 :(得分:1)

您正在循环的$result_array有4个元素,其中没有一个元素具有键category_name的值。你需要做双foreach或更聪明的事情。