PHP - 访问多维数组的问题

时间:2012-08-15 08:28:40

标签: php arrays multidimensional-array

在使用FirePHP查看我正在使用的内容时检索到的多维(?)数组中是否存在问题:

array(
    ['day'] => 'Wed'
    ['is_used'] => 1
    [0] =>
    array(
        ['day'] =>
        'Wed'
        ['title'] =>
        'onsdag denna veckan 2'
        ['content'] =>
        ['price'] =>
    )
    [1] =>
    array(

        ['day'] =>
        'Wed'
        ['title'] =>
        'onsdagslunchen'
        ['content'] =>
        ['price'] =>
        123123
    )
)

如果有任何意义,我想在数组中使用0,1数组......?或者这个阵列坏了吗?

当我尝试

foreach ($foo as $bar){
    echo $bar
}

我得到4个结果,day,is_used和0,1个数组。

2 个答案:

答案 0 :(得分:2)

代码正确返回值。它返回$foo数组的第一个子节点,它们是:

day
is_used
0
1

dayis_used是字符串,但由于01是数组,因此您需要再次遍历它们以获取其值:

foreach ($foo as $fooKey=>$bar){
    if(is_array($bar))
        // cycle through the array
        foreach ($bar as $key=>$value)
            // Echo out the string of the array
            echo "$fooKey $key = $value<br />";
        }
    } else {
        // Echo out the string
       echo "$fooKey = $bar<br />";
    }
}

这应该反映出以下内容:

day = Wed
is_used = 1
0 day = Wed
0 title = onsdag denna veckan 2
0 content =
0 price =
1 day = Wed
1 title = onsdagslunchen
1 content =
1 price = 123123

答案 1 :(得分:0)

也许这就是你想要的:

foreach ($my_array as $key=>$val) {
    if (is_numeric($key) {
        // do something with $val (where $val is an array in the example)
    }
}