如何将树阵列转换为平面阵列?

时间:2016-10-30 14:01:21

标签: php arrays

我有一个类似树状的阵列,我需要将其转换为平面阵列,但我无法使其正常工作。

我正在尝试使用此代码:

$fakepages = array();
    $fakepages[0] = array('id' => 1, 'parent_id' => 0, 'title' => 'Parent Page');
    $fakepages[1] = array('id' => 2, 'parent_id' => 1, 'title' => 'Sub Page');
    $fakepages[2] = array('id' => 3, 'parent_id' => 2, 'title' => 'Sub Sub Page');
    $fakepages[3] = array('id' => 4, 'parent_id' => 3, 'title' => 'Another Parent Page');
    $fakepages[4] = array('id' => 5, 'parent_id' => 0, 'title' => 'Another Parent Page 5');
    $fakepages[5] = array('id' => 6, 'parent_id' => 2, 'title' => 'Another Parent Page 5');

    $tree = $this->buildTree($fakepages);
    return $tree;

private function buildTree(array $elements, $parentId = 0) {
    $branch = array();

    foreach ($elements as $element) {
        if ($element['parent_id'] == $parentId) {
            $children = $this->buildTree($elements, $element['id']);
            if ($children) {
                $element['children'] = $children;
            }
            $branch[] = $element;
        }
    }

    return $branch;
}

这是我的排序(或合并或......?)代码。我的代码存在什么问题?我如何解决这个问题,并在左图中进行修改?

private function findchild($trees)
{
    $arr = array();

    foreach ($trees as $tree) {

        if (isset($tree['children'])) {
            $this->mes[] = ['id'=>$tree['id'],'parent_id'=>$tree['parent_id']];
            $arr[] = $this->findchild($tree['children']);
        }
        else{
            $this->mes[] = ['id'=>$tree['id'],'parent_id'=>$tree['parent_id']];
            $arr[] = $tree;
        }
        return $arr;
    }
}
private $mes = [];

我有正确的部分,但需要将其转换为左侧部分:

enter image description here

1 个答案:

答案 0 :(得分:2)

您可以使用此PHP函数,该函数假定您的数据是标准类对象的数组:

function flatten($arr) {
    $result = [];
    foreach($arr as $item) {
        if (isset($item->children))
            $result = array_merge($result, flatten($item->children));
        unset($item->children);
        $result[] = $item;  
    }
    return $result;
}

当然,如果您的原始值是JSON,则需要首先对其进行解码,然后才将其传递给此函数,如下所示:

$arr = json_decode($json);
// Flatten it
$arr = flatten($arr);
// Optionally sort the result
usort($arr, function($a, $b) { return $a->id - $b->id; });

eval.in

上查看它

如果您的数据由关联数组(而不是"对象")组成,则代码需要使用括号表示而不是->

function flatten($arr) {
    $result = [];
    foreach($arr as $item) {
        if (isset($item['children']))
            $result = array_merge($result, flatten($item['children']));
        unset($item['children']);
        $result[] = $item;
    }
    return $result;
}

和排序:

usort($arr, function($a, $b) { return $a['id'] - $b['id']; });
相关问题