reenadak icon

Create a nested array

reenadak | PRO | 09/25/17 06:49:15 PM UTC | 0 ⭐ | 286 👁️ | Never ⏰ | []
PHP |

790 B

|

None

|

0 👍

/

0 👎

http://creative-punch.net/2014/01/creating-nested-array-items-parent-ids/
http://stackoverflow.com/questions/9996427/getting-a-list-of-children-from-an-array-with-parents-without-recursion-in-php
 
// Create a nested array.
function makeNested($source) {
    $nested = array();
 
    foreach ( $source as &$s ) {
        if ( is_null($s['parent_id']) ) {
            // no parent_id so we put it in the root of the array
            $nested[] = &$s;
        }
        else {
            $pid = $s['parent_id'];
            if ( isset($source[$pid]) ) {
                // If the parent ID exists in the source array
                // we add it to the 'children' array of the parent after initializing it.
 
                if ( !isset($source[$pid]['children']) ) {
                    $source[$pid]['children'] = array();
                }
 
                $source[$pid]['children'][] = &$s;
            }
        }
    }
    return $nested;
}

Comments