1

我有一个名为的多维数组$test

Array (
    [First item] => Array (
        [screen] => 2
        [1] => 2
        [2] => 2
        [3] => 2
        [4] => 2
    )
    [Second Item] => Array (
        [screen] => 3
        [1] => 3
        [2] => 3
        [3] => 3
        [4] => 3
    )
) 

我正在尝试获取密钥:screen, 1, 2, 3, 和4.
它们对于First item和是相同的Second item。你知道我如何遍历这个数组来获取这些值吗?所以,基本上是在我的多维数组中获取第一个数组的键。谢谢!

4

3 回答 3

1

这个怎么样:

$keys = array_keys($test['First item']);

或者,如果您想手动执行此操作:

$keys = array();
foreach($test['First item'] as $key => $value) {
    $keys[] = $key;
}
于 2013-10-31T19:29:05.163 回答
1

那将是这样的:

$keys = array_keys(reset($your_array));

reset()获取数组的第一个值和array_keys()结果数组的键。

您可能希望使用临时变量将其分成两行以避免严格的警告。

于 2013-10-31T19:29:25.500 回答
0

这取决于您要归档的内容:

$test = Array (
    "First item" => Array (
    "screen" => 2,
        1 => 2,
        2 => 2,
        3 => 2,
        4 => 2,
    ),
    "Second Item" => Array (
    "screen" => 3,
        1 => 3,
        2 => 3,
        3 => 3,
        4 => 3,
    )
);

获取所有密钥

$vals = [];
foreach($test as $k=>$v){
    $vals = array_merge($vals, array_keys($v));
}

这将为您带来:

Array
(
    [0] => screen
    [1] => 1
    [2] => 2
    [3] => 3
    [4] => 4
    [5] => screen
    [6] => 1
    [7] => 2
    [8] => 3
    [9] => 4
)

分隔在另一个多维数组中:

foreach($arr as $k=>$v){
    $vals[] = array_keys($v);
}

只有唯一键:

foreach($test as $k=>$v){
    $vals = array_unique(array_merge($vals, array_keys($v)));
}
于 2013-10-31T19:47:53.873 回答