PHP Traversing Function to turn single array into nested array with children - based on parent id

arrays, php, recursion, tree, tree-traversal

Solution

Give this a go (tested under php 5.2):

$inArray = array(
    array('ID' => '1', 'parentcat_ID' => '0'),
    array('ID' => '2', 'parentcat_ID' => '0'),
    array('ID' => '6', 'parentcat_ID' => '1'),  
    array('ID' => '7', 'parentcat_ID' => '1'),
    array('ID' => '8', 'parentcat_ID' => '6'),          
    array('ID' => '9', 'parentcat_ID' => '1'),  
    array('ID' => '13', 'parentcat_ID' => '7'),
    array('ID' => '14', 'parentcat_ID' => '8'),     
);

function makeParentChildRelations(&$inArray, &$outArray, $currentParentId = 0) {
    if(!is_array($inArray)) {
        return;
    }

    if(!is_array($outArray)) {
        return;
    }

    foreach($inArray as $key => $tuple) {
        if($tuple['parentcat_ID'] == $currentParentId) {
            $tuple['children'] = array();
            makeParentChildRelations($inArray, $tuple['children'], $tuple['ID']);
            $outArray[] = $tuple;   
        }
    }
}

$outArray = array();
makeParentChildRelations($inArray, $outArray);

print_r($outArray);

Problem

I have an array similar to this: ``` Array ( Array ( [ID] => 1 [parentcat_ID] => 0 ), Array ( [ID] => 2 [parentcat_ID] => 0 ), Array ( [ID] => 6 [parentcat_ID] => 1 ), Array ( [ID] => 7 [parentcat_ID] => 1 ), Array ( [ID] => 8 [parentcat_ID] => 6 ), Array ( [ID] => 9 [parentcat_ID] => 1 ), Array ( [ID] => 13 [parentcat_ID] => 7 ), Array ( [ID] => 14 [parentcat_ID] => 8 ) ) ``` But I need a function to recursively put each item into a 'children' array inside the relevant parent array. So it would look more like this: ``` Array ( Array ( [ID] => 1 [parentcat_ID] => 0 [children] => Array ( Array ( [ID] => 6 [parentcat_ID] => 1 [childen] => Array ( Array ( [ID] => 8 [parentcat_ID] => 6 [children] => Array ( Array ( [ID] => 14 [parentcat_ID] => 8 ) ) ) ) ), Array ( [ID] => 7 [parentcat_ID] => 1 [children] => Array( Array ( [ID] => 13 [parentcat_ID] => 7 ) ) ), Array ( [ID] => 9 [parentcat_ID] => 1 ) ) ) Array ( [ID] => 2 [parentcat_ID] => 0 ) ) ``` I hope that makes sense!

Original source