This question doesn't necessarily have to be related to PHP or MongoDB.
I have MongoDB database with categories collection. Documents inside collection looks like below
{
title : 'Parent 1',
cat_id : '_ABC1',
level : 1
}
{
title : 'Parent 2',
cat_id : '_ABC2'
level : 1
}
{
title : 'Child 1',
cat_id : '_ABC1_CEF1'
level : 2
}
{
title : 'Child 2',
cat_id : '_ABC1_CEF2'
level : 2
}
{
title : 'Child Child 1',
cat_id : '_ABC1_CEF1_GHI1'
level : 3
}
{
title : 'Child Child 2',
cat_id : '_ABC1_CEF1_GHI2'
level : 3
}
Nesting Now, what I want to do in PHP is get nested array(s) like
$array = array(
array(
'title' => 'Parent 1',
'cat_id' => '_ABC1',
'sub' => array(
'title' => 'Child 1',
'cat_id' => '_ABC1_CEF1',
'sub' => array(
array(
'title' => 'Child Child 1',
'cat_id' => '_ABC1_CEF1_GHI1'
),
array(
'title' => 'Child Child 2',
'cat_id' => '_ABC1_CEF1_GHI2'
)
)
)
),
...
...
)
For that I am using following algorithm (fetch nested level = N) (N is a fetching parameter number that tells iterator, how deep array has to be fetched)
$array_holder = array();
foreach(MongoGetLevel1Cats as $parent){
$parent['sub'] = array();
foreach(MongoGetLevel2Cats as $child){
$child['sub'] = array();
foreach(MongoGetLevel3Cats as $child_child){
$child_child['sub'] = array();
...
...
array_push($child['sub'], $child_child);
}
array_push($parent['sub'], $child);
}
array_push($array_holder, $parent);
}
Return $array_holder;
As this function will give me the desired result but I don't have control over the deep nested level. If have to fetch nested level of order 100, I have to write foreach loop insider foreach loop for 100 times. Also I don't know performance wise this strategy will be good or not.
Does anybody have any idea how we solve this more strategically? Perhaps with for & foreach loop in combination which doesn't involve nesting foreach loop?