使用整数索引访问多维关联数组

时间:2017-03-21 18:40:14

标签: php arrays multidimensional-array associative-array

假设我有一个看起来像这样的关联数组:

$arr = array(
    'a' => array(
            'b' => 'b',
            'c' => 'c',
            'd' => array(
                    'e' =>'e'
            ),
            'f' => 'f',
            'g' => 'g'
    ),
    'h' => 'h',
    'i' => array(
            'j' => 'j',
            'k' => 'k'
    )
);

现在我想使用整数索引访问数组元素:

0 will return array of key 'a'  
1 will return array of key 'b'
2 will return array of key 'c'
3 will return array of key 'd'
4 will return array of key 'e'
..
11 will return array of key 'k'

我尝试使用以下代码通过递归来实现此目的:

function getElement($arr, $id)
{
    static $counter = 0;

    foreach($arr as $key => $val){
        $varNum = count($val);
        $total = $counter + $varNum;
        if($counter == $id){
            return $val;
        }
        elseif($total > $id){
            $counter++;
            $res = getElement($val, $id);
            return $res;
        }
        $counter++;
    }
}

然而,从索引4开始,功能失败 有什么建议吗?

1 个答案:

答案 0 :(得分:1)

使用array_walk_recursive

$list = [];

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

print_r($list);

会返回类似的内容:

Array
(
    [0] => b
    [1] => c
    [2] => e
    [3] => f
    [4] => g
    [5] => h
    [6] => j
    [7] => k
)

现在要返回完整的键列表,您可以使用以下函数:

function walk_recursive($arr, &$list = [])
{
    foreach ($arr as $k => $ar) {
        if (is_array($ar)) {
            $list[] = $k;
            walk_recursive($ar, $list);
        } else {
            $list[] = $ar;
        }
    }
    return $list;
}
print_r(walk_recursive($arr));

这输出如下:

Array
( 
    [0] => a
    [1] => b
    [2] => c
    [3] => d
    [4] => e
    [5] => f
    [6] => g
    [7] => h
    [8] => i
    [9] => j
    [10] => k
)

直播示例:https://3v4l.org/Wv0nL