Search code examples
phparrayspositionkey

php get array element by position instead of numeric key


I have a script that sorts input taking into account parent-child relations and the given display-order of each. A simplified array could look like this (the actual array has sub-arrays for children as well)

$output = Array
(
    [7] => first array
    [3] => second array
    [1] => last array
)

In which the keys are the correspondings id's of the input. Now I wish to pass through this array from top to bottom in a while loop. I am not using foreach because if it has children multiple elements should be processed together, and not come again in the next 'loop'.

function recursive_func($array){
    while ($i<=count($array)){
        if (isset($array[$i]['children'])){
             ?><div><?php
             recursive_function($array[$i]['children']);
             $i++;
             recursive_function($array[$i]['children']);
             $i++;
             ?></div><?php
             }
           else{
             ?><div>Something</div><?php
             $i++;
          }
     }
}

Clearly $array[$i]['children'] aren't the children of the i'th element (by position), but of the key with value i. How can I pass through this array in the order as in $output?


Solution

  • As Garr Godfrey suggested, you can solve this with array_keys() like so

    function recursive_func($array){
        $keys = array_keys($array);
        for ($i=0; $i<count($keys); $i++) {
            if (isset($array[ $keys[$i] ]['children'])) {
                recursive_func($array[ $keys[$i] ]['children']);
                $i++;
                recursive_func($array[ $keys[$i] ]['children']);
            } else {
                //sth, no $i++ here!
            }
        }
    }
    

    Because I am using a for loop here, the $i++ inside the loop will make it possible for you to skip one element