dtoq41429
2015-09-21 05:20 浏览 50
已采纳

获取数组中每个元素的最后一个维度

I have an array that might 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 the strings, like this:

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

Here is a recursive function I made. It seems to work. But I'm not sure that I'm doing it right, as far as declaring the static, and when to unset the static var (in case I want to use the function again, I dont want that old static array)

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

How do I make sure each time I call the function, the $out var is fresh, every time? Is there a better way of doing this?

Maybe check if we're 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;
}
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答 默认 最新

  • 已采纳
    dongteng0748 dongteng0748 2015-09-21 06:10

    Your last version will probably work correctly. However, if you want to get rid of the static variable you could also do it like this:

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

    The key here is, that you actually return the so far found values at the end of your function but so far you have not 'picked them up' in the calling part of your script. This version works without any static variables.

    点赞 评论 复制链接分享
  • douyun3631 douyun3631 2015-09-21 07:28

    I'll simply use array_walk_recursive over here instead like as

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

    Demo

    点赞 评论 复制链接分享

相关推荐