php将平面家庭列表转换为树

时间:2016-12-17 16:37:02

标签: php arrays tree

这个有点Q& A风格...

我一直在寻找这种情况,找不到任何解决方案,所以我自己建立。

我花了几天时间才能获得满足我需求的代码,但现在我想知道是否有更有效的方法:

$data = [
  ['a','aa','aaa'],
  ['a','aa','aab'],
  ['a','aa','aac'],
  ['a','ab'],
  ['a','ac','aca'],
  ['b','ba'],
  ['b','bb'],
  ['b','bc'],
];


function tree($values){
  $on_end = sizeof($values) == 1 && sizeof($values[0]) == 0;
  if ( $on_end ) return null;

  $tree1 = [];
  $tree2 = [];

  foreach ($values as $a){
    $parent = $a[0];
    //remove the first column
    array_shift($a);
    $tree1[ $parent ][] = $a;
  }

  foreach ($tree1 as $parent => $b){
    $tree2[ $parent ] = tree( $b );

  }

  return $tree2;

}


echo "<pre>".print_r(tree($data),true)."</pre>";

这是结果:

Array
(
[a] => Array
    (
        [aa] => Array
            (
                [aaa] => 
                [aab] => 
                [aac] => 
            )

        [ab] => 
        [ac] => Array
            (
                [aca] => 
            )

    )

[b] => Array
    (
        [ba] => 
        [bb] => 
        [bc] => 
    )

)

如果有人有更好的,请发布!

1 个答案:

答案 0 :(得分:1)

你有一个最短的解决方案......但它使用eval函数 erk

<?php

$data = [
  ['a','aa','aaa'],
  ['a','aa','aab'],
  ['a','aa','aac'],
  ['a','ab'],
  ['a','ac','aca'],
  ['b','ba'],
  ['b','bb'],
  ['b','bc'],
];

function arrayToTree_eval(array $source, $defaultValue = null) {
    $tree = [];

    foreach( $source as $values ) {
        eval(sprintf('$tree%s = $defaultValue;', '["' . implode('"]["', $values) . '"]'));
    }

    return $tree;
}

var_dump( arrayToTree_eval($data) );
  

7行代码,然后跳!

array (size=2)
  'a' => 
    array (size=3)
      'aa' => 
        array (size=3)
          'aaa' => null
          'aab' => null
          'aac' => null
      'ab' => null
      'ac' => 
        array (size=1)
          'aca' => null
  'b' => 
    array (size=3)
      'ba' => null
      'bb' => null
      'bc' => null

:)