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

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

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 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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料