使用关系键将一维数组转换为嵌套数组

时间:2012-07-20 09:20:08

标签: php object language-agnostic multidimensional-array

假设我的数组中包含代表id的键和代表parent的值:

4  => 0
2  => 0
5  => 2
6  => 5
8  => 0
9  => 0
10 => 8
12 => 0
13 => 0
14 => 0
18 => 7
19 => 18
20 => 19
21 => 20
22 => 21
23 => 22
24 => 23
28 => 20
7  => 5

您也可以将其视为对象:

  { 
   id     : 4,
   parent : 0
  } // etc...

我想要实现的多维数组是:

4  => 0
2  => 5  
        => 6
        => 7
            => 18
                 => 19
                      => 20
                           => 21
                                 => 22
                                       => 23
                                             => 24
                           => 28
8  => 10
9  => 0
12 => 0
13 => 0
14 => 0

我将如何做到这一点?

1 个答案:

答案 0 :(得分:3)

如果您编写一个小帮助函数来将数据重新修改为类似于以下结构:

$input = array(
  array('id' => '4', 'parent' => '0'),
  // ...
);

可以通过以下方式实现:

$data = array_map(function ($entry) {
  list($id, $parent) = array_map('trim', explode('=>', $entry));
  return array(
    'id' => $id,
    'parent' => $parent
  );
}, explode("\n", $data));

然后你可以使用我在类似question中使用的函数:

function flatToNested($d, $r = 0, $p = 'parent', $k = 'id', $c = 'children') {
  $m = array();
  foreach ($d as $e) {
    isset($m[$e[$p]]) ?: $m[$e[$p]] = array();
    isset($m[$e[$k]]) ?: $m[$e[$k]] = array();
    $m[$e[$p]][] = array_merge($e, array($c => &$m[$e[$k]]));
  }
  return $m[$r];
}

生成一个嵌套数组:

$nested = flatToNested($data);

演示:http://codepad.viper-7.com/HAZxaA