简体   繁体   中英

how can i convert an array to nested array in php

i have a function in my project that returns an array like this

array (size=6)
  0 => 
    array (size=4)
      'id' => string '1' (length=1)
      'user_id' => string '1' (length=1)
      'parent_id' => string '0' (length=1)
      'name' => string 'jack' (length=4)
  1 => 
    array (size=4)
      'id' => string '2' (length=1)
      'user_id' => string '6' (length=1)
      'parent_id' => string '1' (length=1)
      'name' => string 'jill' (length=4)
  2 => 
    array (size=4)
      'id' => string '3' (length=1)
      'user_id' => string '7' (length=1)
      'parent_id' => string '2' (length=1)
      'name' => string 'mary' (length=4)
  3 => 
    array (size=4)
      'id' => string '4' (length=1)
      'user_id' => string '2' (length=1)
      'parent_id' => string '1' (length=1)
      'name' => string 'scriptfloor' (length=11)

i would like to convert this into a nested array based on parent id into this

{
  "id": "1",
  "user_id": "1",
  "parent_id": "0",
  "name": "jack",
  "children": [
    {
      "id": "2",
      "user_id": "6",
      "parent_id": "1",
      "name": "jill"
    },
    {
      "id": "4",
      "user_id": "2",
      "parent_id": "1",
      "name": "scriptfloor"
    },
    {
      "id": "6",
      "user_id": "3",
      "parent_id": "1",
      "name": "silas"
    }
  ]
}

so far i have only gone up to one nested level. i would like to be able to make a multi-dimensional array of n-levels . i need this for to build tree hierarchy of users and the users who referred them .Any help will be appreciated

i have used this function where $items is the unsorted array

for ( $count = 0; $count < count( $items ); $count ++ ) {
    if ( count( $items[ $count ] ) > 0 ) {
        foreach ( $items[ $count ] as $itm ) {
            if ( $itm['parent_id'] == $tree['user_id'] ) {
                $tree['children'][] = $itm;
            }

        }

    }

}

This problem reveals lot of things to now (reference variable, remove item from array, array structure, continue instruction, ...).

As a workaround below, i advice you to loop on the $items list a first time, next you loop again on the same list to fill children list for each parent, you need to compare id and parent_id, if it's true you inject item on parent's children list, you remove the item to clean your array and then you end statement for current $item iteration.

I hope it's clear enought.

foreach($items as $k => $item) {
   foreach($items as $j => $parent) {
       if ($item['parent_id'] === $parent['id']) {
           $parents[$j]['children'][] = $item;
           unset($items[$k]);
           continue 2;
       }
   }
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM