我需要对对象数组进行分层排序。数据如下:
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
属性是指另一个对象的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;
}
}
}
,但我无法在多层次结构中使用它。
如何对数据进行排序以获得所需的结果?
我会使用递归函数。你所做的并不是真正的分类。你正在建造一个树状结构。假设您的原始对象在一个名为$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;
}