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条)

报告相同问题?

悬赏问题

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