Creating a nested array from items with parent IDs


/ Published in: PHP
Save to your folder(s)

Creating a nested array from items with parent IDs.
This is useful for when you have a website working with multiple categories with parent categories. But it can be applied anywhere, really!


Copy this code and paste it in your HTML
  1. function makeNested($source) {
  2. $nested = array();
  3.  
  4. foreach ( $source as &$s ) {
  5. if ( is_null($s['parent_id']) ) {
  6. // no parent_id so we put it in the root of the array
  7. $nested[] = &$s;
  8. }
  9. else {
  10. $pid = $s['parent_id'];
  11. if ( isset($source[$pid]) ) {
  12. // If the parent ID exists in the source array
  13. // we add it to the 'children' array of the parent after initializing it.
  14.  
  15. if ( !isset($source[$pid]['children']) ) {
  16. $source[$pid]['children'] = array();
  17. }
  18.  
  19. $source[$pid]['children'][] = &$s;
  20. }
  21. }
  22. }
  23. return $nested;
  24. }

URL: http://creative-punch.net/2014/01/creating-nested-array-items-parent-ids/

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.