Posted By

CreativePunch on 01/03/14


Tagged

php sort array categories parentid


Versions (?)

Creating a nested array from items with parent IDs


 / Published in: PHP
 

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

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!

  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. }

Report this snippet  

You need to login to post a comment.