fireinspace
fireinspace

Reputation: 197

Returning variables in array with unknown depth

I'm trying to write a loop that will go through an array of any depth and assign the key/value pair to variables. The problem is that the function is recursive, so when I eventually have to return the variables, it kills the loop and I'm only left with the first iteration. Here's the code. Any help?

function recursive($a, $l = 1){
    if(is_array($a)){
        foreach($a as $k => $v){
            if(is_array($v)){
                recursive($v, $l + 1);
            }else{
                $keys[] = $k;
                $values[] = $v;
            }       
        }
    }
    return array($keys, $values);
}

Upvotes: 2

Views: 597

Answers (2)

jedrzej.kurylo
jedrzej.kurylo

Reputation: 40919

Use PHP's array_walk_recursive function:

$data = array('a' => 3, 'b' => array('d' => 5)); //this is your array of any depth
$keys = array();
$values = array();

array_walk_recursive($data, function($v, $k) use (&$keys, &$values) {
    $keys[] = $k;
    $values[] = $v;
});

print_r($keys);
print_r($values);

Upvotes: 2

Daniel
Daniel

Reputation: 340

One option is call function in do-while loop and if function find a match then delete it.

$copy = $array;
do{
    $find = false;
    $result = recursive($copy, $find);
}while($find)

function recursive(&$a, &$find, $l = 1){
    if(is_array($a)){
        foreach($a as $k => $v){
            if(is_array($v)){
                recursive($v, $find, $l + 1);
            }else{
                $keys[] = $k;
                $values[] = $v;
                unset($a[$k]);
                $find = true;
            }       
        }
    }
    return array($keys, $values);
}

Upvotes: 0

Related Questions