我需要分层次地对对象数组进行排序。数据如下所示:
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)
我想创建一个多维数组来显示" parent和children"的这种层次结构。每个对象的parent
属性引用另一个对象的term_id
。
结果看起来像这样:
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)
到目前为止,我已经提出了这个代码:
$sortedCategories = array();
foreach($shopCategories as $shopCategory) {
$tmp = $shopCategory;
foreach($shopCategories as $category) {
if ($tmp->term_id == $category->parent) {
$tmp->children[] = $category;
$sortedCategories[] = $tmp;
}
}
}
,但我无法使用多级层次结构。
如何对数据进行排序以达到预期效果?
答案 0 :(得分:2)
我会使用递归函数。它并没有真正排序你正在做的事情。您正在构建树结构。假设您的原始对象位于名为$a
的数组中,并且您希望将新树称为$b
。此功能的作用是添加您正在处理的当前父级的孩子。每次添加一个孩子时,它也会自称添加该对象的孩子。因此,递归。你从0的父级开始,我假设这意味着"没有父级"。
$b = build_tree($a);
function build_tree(&$a, $parent=0)
{
$tmp_array = array();
foreach($a as $obj)
{
if($obj->parent == $parent)
{
// The next line adds all children to this object
$obj->children = build_tree($a, $obj->term_id);
$tmp_array[] = $obj
}
}
// You *could* sort the temp array here if you wanted.
return $tmp_array;
}