Get the last dimension of each array element

I have an array that can be any depth or number of elements:

$ra['a'] = 'one';
$ra['b']['two'] = 'b2';
$ra['c']['two']['three'] = 'c23';
$ra['c']['two']['four'] = 'c24';
$ra['c']['five']['a'] = 'c5a';

I want to have an array of strings, for example:

array (
  0 => 'one',
  1 => 'b2',
  2 => 'c23',
  3 => 'c24',
  4 => 'c5a',
)

Here is the recursive function I made. It seems to work. But I'm not sure that I am doing it right while declaring static, and when I need to cancel the static var (in case I want to use this function again, I do not need a static static array)

function lastthinggetter($ra){
    static $out;
    foreach($ra as $r){
        if(is_array($r))
             lastthinggetter($r);
        else
            $out[] = $r;    
    }
    return $out;
}

How can I make sure that every time I call a function, the variable $ out var is fresh every time? Is there a better way to do this?

Maybe check if we are in recursion?

function lastthinggetter($ra, $recurse=false){
    static $out;
    foreach($ra as $r){
        if(is_array($r))
             lastthinggetter($r, true);
        else
            $out[] = $r;    
    }
    $tmp = $out;
    if(!$recurse)
        unset($out);
    return $tmp;
}
+4
source share
2 answers

, , . , static, :

function getleaves($ra) {
    $out=array();
    foreach($ra as $r) {
        if(is_array($r)) {
            $out=array_merge($out,getleaves($r));
        }
        else {
            $out[] = $r;
        }
    }
    return $out;
}

, , " " script. - .

+2

array_walk_recursive ,

array_walk_recursive($ra, function($v)use(&$result) {
    $result[] = $v;
});

+1

Source: https://habr.com/ru/post/1608263/


All Articles