I suffered for days looking for an answer and trying to solve the problme myself but I could not.
I have data in a PHP array with a the key parent_id
as an array. I found how to build a tree but only if it has only ONE parent! But in my case it has multiple parents and it must be nested below every parent.
Here is an example:
Parents
array(
'id' => 1,
'name' => 'Parent 1',
'parent_id' => array()
);
array(
'id' => 2,
'name' => 'Parent 2',
'parent_id' => array()
);
Children
array(
'id' => 3,
'name' => 'Child 1',
'parent_id' => array(1, 2)
);
I want the tree to be built like so:
array(
'id' => 1,
'name' => 'Parent 1',
'parent_id' => array(),
'children' => array(
array(
'id' => 3,
'name' => 'Child 1',
'parent_id' => array(1, 2)
)
),
);
array(
'id' => 2,
'name' => 'Parent 2',
'parent_id' => array(),
'children' => array(
array(
'id' => 3,
'name' => 'Child 1',
'parent_id' => array(1, 2)
)
),
);
Can you suggest a working function that may help me. Thanks in advance.
EDITED (DEMO)
@Jeff Lambert is right. What I did was to loop through elements and if any has parents, I add its ID to a newly created key children .. This way I can retrieve it whenever I want.
function build_tree(array $elements)
{
$indexed = array();
foreach($elements as $element)
{
$element = (array) $element;
$indexed[$element['id']] = $element;
}
$elements = $indexed;
unset($indexed, $element);
foreach($elements as $id => $element)
{
if ( ! empty($element['parent_id']))
{
foreach($element['parent_id'] as $parent)
{
if (isset($elements[$parent]))
{
$elements[$parent]['children'][] = $element['id'];
}
}
}
}
return $elements;
}
Then I only need to create and little function to retrieve element details like so:
function get_element($id, $return = NULL)
{
// Check the element inside the array
if (isset($elements[$id])
{
// In case I want to return a single value
if ($return !== NULL and isset($elements[$id][$return])
{
return $elements[$id][$return];
}
return $elements[$id];
}
return FALSE; // Or NULL, as you wish
}