I need to sort an array of objects hierarchically. The data looks like this:
array (size=54)
0 =>
object(stdClass)[786]
public 'term_id' => string '1' (length=3)
public 'name' => string 'Boots' (length=25)
public 'parent' => string '0' (length=3)
1 =>
object(stdClass)[785]
public 'term_id' => string '2' (length=3)
public 'name' => string 'Dresses' (length=25)
public 'parent' => string '1' (length=3)
2 =>
object(stdClass)[786]
public 'term_id' => string '3' (length=3)
public 'name' => string 'Scarves' (length=25)
public 'parent' => string '2' (length=3)
3 =>
object(stdClass)[785]
public 'term_id' => string '4' (length=3)
public 'name' => string 'Gloves' (length=25)
public 'parent' => string '1' (length=3)
I want to create a multidimensional array that would show this hierarchy of "parent and children". The parent property of each object refers to the term_id of another object.
The result would look something like this:
array (size=54)
0 =>
object(stdClass)[786]
public 'term_id' => string '1' (length=3)
public 'name' => string 'Boots' (length=25)
public 'parent' => string '0' (length=3)
public 'children' => array (size=2)
0 =>
object(stdClass)[785]
public 'term_id' => string '2' (length=3)
public 'name' => string 'Dresses' (length=25)
public 'parent' => string '1' (length=3)
public 'children' => (size=1)
0 =>
object(stdClass)[786]
public 'term_id' => string '3' (length=3)
public 'name' => string 'Scarves' (length=25)
public 'parent' => string '2' (length=3)
1 =>
object(stdClass)[785]
public 'term_id' => string '4' (length=3)
public 'name' => string 'Gloves' (length=25)
public 'parent' => string '1' (length=3)
So far I have come up with this code:
$sortedCategories = array();
foreach($shopCategories as $shopCategory) {
$tmp = $shopCategory;
foreach($shopCategories as $category) {
if ($tmp->term_id == $category->parent) {
$tmp->children[] = $category;
$sortedCategories[] = $tmp;
}
}
}
,but I cannot get it work with the multi-level hierarchy.
How can I sort the data to achieve the desired result?