duanlu9970 2011-12-05 22:11
浏览 16
已采纳

PHP函数用路径获取递归路径密钥

Given an array, I would like a flattened version of the array keys. Each array key would need the 'path' of the array, to that point, appended with an underscore.

An example explains this best.

$arr = array("location"=>0,"details"=>array("width"=>0,"height"=>0,"level"=>array("three"=>0)));

function answer($arr) {....}

the answer function would return this:

array("location","details_width","details_height","details_level_three");

UPDATE:

Here is the work in progress. It will accept an array and return the array keys, but with no depth:

function recursive_keys($input)
{
    $output = array_keys($input);
    foreach($input as $sub){
        if(is_array($sub)){
            $output = array_merge($output, recursive_keys($sub));
        }
    }
    return $output;
}
  • 写回答

2条回答 默认 最新

  • dty47696 2011-12-05 22:54
    关注
    function recursive_keys(array $array, array $path = array()) {
        $result = array();
        foreach ($array as $key => $val) {
            $currentPath = array_merge($path, array($key));
            if (is_array($val)) {
                $result = array_merge($result, recursive_keys($val, $currentPath));
            } else {
                $result[] = join('_', $currentPath);
            }
        }
        return $result;
    }
    

    Demo here: http://codepad.viper-7.com/WQ3UYI

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

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?