Convert flat array to the multi-dimensional

后端 未结 3 726
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:16

    I don't think there is a built-in function in PHP that does this.

    I tried the following code, and it seems to work to prepare the nested array the way you describe:

    $nodes = array();
    $tree = array();
    foreach ($source as &$node) {
      $node["Children"] = array();
      $id = $node["Menu"]["id"];
      $parent_id = $node["Menu"]["parent_id"];
      $nodes[$id] =& $node;
      if (array_key_exists($parent_id, $nodes)) {
        $nodes[$parent_id]["Children"][] =& $node;
      } else {
        $tree[] =& $node;
      }
    }
    
    var_dump($tree);
    

    I wrote a similar algorithm in a PHP class I wrote for my presentation Hierarchical Models in SQL and PHP, but I was using objects instead of plain arrays.

提交回复
热议问题