数组循环 - 无法获取打印密钥

时间:2011-06-07 15:25:32

标签: php arrays loops multidimensional-array

我在$ newarray

中有如下数组
Array
(
    [111] => Array
        (
            [123] => 0
            [124] => 0
            [125] => 0
            [126] => 0
            [127] => 0
            [128] => 0
            [129] => 0
            [130] => 1
            [131] => 1
            [132] => 1
            [133] => 1
            [134] => 1
            [135] => 1
        )

    [222] => Array
        (
            [123] => 0
            [124] => 0
            [125] => 0
            [126] => 1
            [127] => 1
            [128] => 1
            [129] => 1
            [130] => 1
            [131] => 1
            [132] => 1
            [133] => 1
            [134] => 1
            [135] => 1
        )

    [333] => Array
        (
            [256] => 0
            [321] => 0
            [456] => 0
            [489] => 0
            [652] => 1
            [741] => 1
            [965] => 0
        )

)

我需要在foreach中获取键名(在本例中为111,222和333):

以下总是吐出“222”3次,无论我做什么。有什么明显的吗?

foreach($newarray as $value) {
echo key($newarray) . "<br />";
}

输出

222
222
222

2 个答案:

答案 0 :(得分:4)

试试这个:

foreach($newarray as $key => $value)
{
     echo $key . "<br />";
}

答案 1 :(得分:4)

这是使用foreach的正确方法

foreach($newarray as $key=>$value) {
    echo $key . "<br />";
}

或者您可以使用

print_r(array_keys($newarray));