/ Published in: PHP
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!
This is useful for when you have a website working with multiple categories with parent categories. But it can be applied anywhere, really!
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
function makeNested($source) { foreach ( $source as &$s ) { // no parent_id so we put it in the root of the array $nested[] = &$s; } else { $pid = $s['parent_id']; // If the parent ID exists in the source array // we add it to the 'children' array of the parent after initializing it. } $source[$pid]['children'][] = &$s; } } } return $nested; }
URL: http://creative-punch.net/2014/01/creating-nested-array-items-parent-ids/