reenadak

Create a nested array

Sep 25th, 2017
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 0.79 KB | None | 0 0
  1. http://creative-punch.net/2014/01/creating-nested-array-items-parent-ids/
  2. http://stackoverflow.com/questions/9996427/getting-a-list-of-children-from-an-array-with-parents-without-recursion-in-php
  3.  
  4. // Create a nested array.
  5. function makeNested($source) {
  6.     $nested = array();
  7.  
  8.     foreach ( $source as &$s ) {
  9.         if ( is_null($s['parent_id']) ) {
  10.             // no parent_id so we put it in the root of the array
  11.             $nested[] = &$s;
  12.         }
  13.         else {
  14.             $pid = $s['parent_id'];
  15.             if ( isset($source[$pid]) ) {
  16.                 // If the parent ID exists in the source array
  17.                 // we add it to the 'children' array of the parent after initializing it.
  18.  
  19.                 if ( !isset($source[$pid]['children']) ) {
  20.                     $source[$pid]['children'] = array();
  21.                 }
  22.  
  23.                 $source[$pid]['children'][] = &$s;
  24.             }
  25.         }
  26.     }
  27.     return $nested;
  28. }
Add Comment
Please, Sign In to add comment