php如何把一颗树型数组转换成列表数组呢?

唐小明生 发布于 2013/06/06 20:32
阅读 1K+
收藏 0
PHP
$a = array(
    0=>array(
        'id'=>1,
        'name'=>"祖宗1",
        'parent'=>"0",
        'childs'=>array(
            'id'=>2,
            'name'=>"爷爷",
            'parent'=>1,
            'childs'=>array(
                'id'=>3,
                'name'=>"爸爸",
                'parent'=>2,
                'childs'=>array(
                    'id'=>4,
                    'name'=>"儿子",
                    'parent'=>3,
                    'childs'=>array()
                )
             )
         )
    ),
    1=>array(
        'id'=>5,
        'name'=>"祖宗2",
        'parent'=>"0",
        'childs'=>array()
    )
);

/*
  把以上数组遍历成以下格式且按照以下循序排列,且删除childs元素
*/

$b = array(
     0=>array(
        'id'=>1,
        'name'=>"祖宗1",
        'parent'=>0
     ),
     
     1=>array(
        'id'=>2,
        'name'=>"爷爷",
        'parent'=>1
     ),
     
     2=>array(
        'id'=>3,
        'name'=>"爸爸",
        'parent'=>2
     ),
     
     3=>array(
        'id'=>4,
        'name'=>"儿子",
        'parent'=>3
     ),
     
     4=>array(
        'id'=>5,
        'name'=>"祖宗2",
        'parent'=>0
     )
);
加载中
0
MeiKai
MeiKai
给个提示,你可以使用递归
0
唐小明生
唐小明生
 function treelist($array){
  if(!isset($array)||!is_array($array)||empty($array)){
return false;
  }
  static $result_array = array();
  foreach($array as $key=>$value){
if(isset($value['childs'])){
   $result_array[]=$value['childs'];
treelist($value['childs']);
}else{
$result_array[]=$value;
}
        }
     return $result_array; 
 } 
0
唐小明生
唐小明生
我递归不太会,
0
MeiKai
MeiKai
$GLOBALS['person_msg'] = array();

function get_person_msg($arr)
{
    $tmpArr = array();
    foreach ($arr as $key => $value) {
        if (is_array($value)) {
            $GLOBALS['person_msg'][] = $tmpArr;
            get_person_msg($value);
        } else {
            $tmpArr[$key] = $value;
        }
    }
}

foreach ($a as $value1) {
    get_person_msg($value1);
}
print_r($GLOBALS['person_msg']);
//不过这里用了$LOBALS用来进行数据共享,感觉有点鸡肋
0
唐小明生
唐小明生
$b = array();
array_walk($a, $f = function($entry) use (&$b, &$f) {
if (is_array($entry) && !empty($entry)) {
$tmp = $entry;
unset($tmp["childs"]);
$b[] = $tmp;
array_walk($entry, $f);
}
}); 
return $b;
唐小明生
唐小明生
这个更牛b看不懂
返回顶部
顶部