Converting an array from one to multi-dimensional based on parent ID values

前端 未结 2 2046
暖寄归人
暖寄归人 2020-11-30 13:33

I\'ve got a one-dimensional array of objects that represent multi-dimensional data:

array(
    array(
        \"id\" => 45,
        \"parent_id\" => nu         


        
2条回答
  •  醉话见心
    2020-11-30 13:54

    function convertArray ($array) {
      // First, convert the array so that the keys match the ids
      $reKeyed = array();
      foreach ($array as $item) {
        $reKeyed[(int) $item['id']] = $item;
      }
      // Next, use references to associate children with parents
      foreach ($reKeyed as $id => $item) {
        if (isset($item['parent_id'], $reKeyed[(int) $item['parent_id']])) {
          $reKeyed[(int) $item['parent_id']]['children'][] =& $reKeyed[$id];
        }
      }
      // Finally, go through and remove children from the outer level
      foreach ($reKeyed as $id => $item) {
        if (isset($item['parent_id'])) {
          unset($reKeyed[$id]);
        }
      }
      return $reKeyed;
    }
    

    I feel sure this can be reduced to only two loops (combining the second and third) but right now I can't for the life of me figure out how...

    NOTE This function relies on parent_id for items with no parent being either NULL or not set at all, so that isset() returns FALSE in the last loop.

提交回复
热议问题