Nested array. Third level is disappearing

后端 未结 2 936
迷失自我
迷失自我 2020-11-27 08:23

I have that array :

$a = array(
    \"7\" => array(
        \"id\" => 7,
        \"parent\" => 6
    ),
    \"6\" => array(
        \"id\" =>         


        
2条回答
  •  爱一瞬间的悲伤
    2020-11-27 08:54

    Are you sure that output array is correct? Surely the key 2 should be a child of 1 (since 2 has 'parent'=>1)? If this is not the case, I don't understand what are actually trying to do and how the keys all relate to each other.

    If 2 should be a child of 1, this works:

    $keep = array();
    foreach ($a as $k => &$v) {
      // Loop the array first time and create references to
      // structure the array how you want it
      if ($v['parent']) {
        $a[$v['parent']][0] = array($k => &$v);
      } else $keep[] = $k;
    }
    
    foreach ($a as $k => $v) {
      // Loop it again to get rid of non-root nodes from the root
      if (!in_array($k,$keep)) {
        unset($a[$k]);
      }
    }
    
    print_r($a);
    

提交回复
热议问题