Convert flat array to the multi-dimensional

后端 未结 3 731
Happy的楠姐
Happy的楠姐 2020-11-27 04:15

I have an array with tree data (by parent id). I want to convert it to multidimensional array. What is the best way to achieve that? Is there any short function for that?

3条回答
  •  盖世英雄少女心
    2020-11-27 05:04

    I wrote this variant considering root parent_id is 0 or missing. No matter children after parents in DB ($source) or not.

    $source_by_id = array();
    foreach ($source as &$row){
      $source_by_id[$row['id']] = &$row;
    }
    foreach ($source_by_id as $id => &$row){
      $source_by_id[ intval($row['parent_id']) ]['children'][$id] = &$row;
    }
    // remove cycling itself
    unset($source_by_id[0]['children'][0]);
    
    $result = $source_by_id[0]['children'];
    

    Result array keys are appropriate ids. Enjoy!

提交回复
热议问题