php - Get the last dimension of each element of an array -
i have array might 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 have array of strings, this:
array (   0 => 'one',   1 => 'b2',   2 => 'c23',   3 => 'c24',   4 => 'c5a', )   here recursive function made. seems work. i'm not sure i'm doing right, far declaring static, , when unset static var (in case want use function again, dont want old static array)
function lastthinggetter($ra){     static $out;     foreach($ra $r){         if(is_array($r))              lastthinggetter($r);         else             $out[] = $r;         }     return $out; }   how make sure each time call function, $out var fresh, every time? there better way of doing this?
maybe check if we're in recursion?
function lastthinggetter($ra, $recurse=false){     static $out;     foreach($ra $r){         if(is_array($r))              lastthinggetter($r, true);         else             $out[] = $r;         }     $tmp = $out;     if(!$recurse)         unset($out);     return $tmp; }      
your last version work correctly. however, if want rid of static variable this:
function getleaves($ra) {     $out=array();     foreach($ra $r) {         if(is_array($r)) {             $out=array_merge($out,getleaves($r));         }         else {             $out[] = $r;         }     }     return $out; }   the key here is, return far found values @ end of function far have not 'picked them up' in calling part of script. version works without static variables.
Comments
Post a Comment