PHP数组获取当前元素

时间:2017-03-23 12:43:31

标签: php arrays multidimensional-array associative-array

我有一个无法处理的有趣任务。我有一个PHP数组,它是多维,关联或混合后自动生成的。

$data['sport']['basketball']['team']['player']['position']['hand']['name']['finalelement']
$data['sport']['basketball']['team']['player'][0]['position']['hand']['name']['finalelement']
$data['sport']['basketball']['team']['player'][0]['position']['hand']['name'][0]['finalelement']
$data['sport']['basketball']['team']['player']['position']['hand']['name'][0]['finalelement']

目标是,无论是多维还是关联到达最终元素。有一种简单的方法,如果条件很少。但我想问一下你是否知道是否还有更多的方法?

2 个答案:

答案 0 :(得分:2)

下一个代码返回第一个不是数组的最深值:

$data['sport']['basketball']['team']['player']['position']['hand']['name'][0]['finalelement'] = 'end';

$current = $data;

while (is_array($current)) {
    $current = array_values($current)[0];
}

print $current; // end

答案 1 :(得分:2)

您可以按如下方式使用array_walk_recursive

$data['sport']['basketball']['team']['player']['position']['hand']['name']['finalelement'] = 'e1';
$data['sport']['basketball']['team']['player'][0]['position']['hand']['name']['finalelement'] = 'e2';
$data['sport']['basketball']['team']['player'][0]['position']['hand']['name'][0]['finalelement'] = 'e3';
$data['sport']['basketball']['team']['player']['position']['hand']['name'][0]['finalelement'] = 'e4';

$list = [];
array_walk_recursive($data, function ($value, $key) use (&$list) {
    $list[] = $value;
});

print_r($list);

这将输出以下内容:

Array (
    [0] => e1
    [1] => e4
    [2] => e2
    [3] => e3
)