dsk95913 2012-09-06 21:29
浏览 67
已采纳

具有多个叶节点的PHP Flatten Array

What is the best way to flatten an array with multiple leaf nodes so that each full path to leaf is a distinct return?

array("Object"=>array("Properties"=>array(1, 2)));

to yield

  1. Object.Properties.1
  2. Object.Properties.2

I'm able to flatten to Object.Properties.1 but 2 does not get processed with recursive function:

function flattenArray($prefix, $array)
{
    $result = array();
    foreach ($array as $key => $value)
    {
        if (is_array($value))
            $result = array_merge($result, flattenArray($prefix . $key . '.', $value));
        else
            $result[$prefix . $key] = $value;
    }   
    return $result;
}

I presume top down will not work when anticipating multiple leaf nodes, so either need some type of bottom up processing or a way to copy array for each leaf and process (althought that seems completely inefficient)

  • 写回答

3条回答 默认 最新

  • dpwbc42604 2012-09-06 22:00
    关注
    function flatten(array $data, $separator = '.') {
      $result = array();
      $stack = array();
      $path = null;
    
      reset($data);
      while (!empty($data)) {
        $key = key($data);
        $element = $data[$key];
        unset($data[$key]);  
        if (is_array($element)) {
          if (!empty($data)) {
            $stack[] = array($data, $path);
          }
          $data = $element;
          $path .= $key . $separator;
        } else {
          $result[$path . $key] = $element;
        }
    
        if (empty($data) && !empty($stack)) {
          list($data, $path) = array_pop($stack);
        }
      }
      return $result;
    }
    
    var_dump(flatten(array("Object"=>array("Properties"=>array(1, 2)))));
    

    Output:

    array(2) {
      ["Object.Properties.0"]=>
      int(1)
      ["Object.Properties.1"]=>
      int(2)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 关于大棚监测的pcb板设计
  • ¥20 sim800c模块 at指令及平台
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计