2

Assuming I have an associative array which looks like this:

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

Now I want to access array elements using integer-index:

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'

I have tried to accomplish this by recursion using the following code:

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++;
    }
}

However from index 4 the function fails.
any suggestions?

1 Answer 1

1

Using array_walk_recursive:

$list = [];

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

print_r($list);

Will return something like:

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

now to return a full list of keys , you may use the following function:

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));

this output the following :

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

live example: https://3v4l.org/Wv0nL

Sign up to request clarification or add additional context in comments.

13 Comments

omg, give me a five minutes, i've wrote this code using my mobile from SO mobile app
I edited in to use a reference, so it works but not the way OP specified.
i knew that, i was going to update my answer right now, thank you for that
@AbraCadaver now i've added new function to get the full list as the OP specified;
I think this will work as OP stated if you change $list[] = $k; to $list[] = $ar;. Good one.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.