PHP将平面家庭列表转换为树 [英] php convert flat family list to tree

查看:46
本文介绍了PHP将平面家庭列表转换为树的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个有点问与答的风格...

this one is a little Q&A-style...

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

i've been searching for this situation and couldn't find any solution, so i build my own.

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

it took me a few days to get a working code for my needs, but now i am wondering if there's a more efficient way:

$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] => 
    )

)

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

if anybody got a better one, please post it!

推荐答案

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

You have a shortest solution ... but it's using eval function 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行代码,然后跳!

7 lines of code, and hop !

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

:)

这篇关于PHP将平面家庭列表转换为树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆