根据父子关系重新构造数组 [英] Re-structure array based on parent/child relationship

查看:121
本文介绍了根据父子关系重新构造数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有以下数组结构:

Array
(
    [0] => Array
        (
            [id] => 83
            [parent_id] => 0
            [title] => Questionnaire one
        )

    [1] => Array
        (
            [id] => 84
            [parent_id] => 0
            [title] => Questionnaire two
        )

    [2] => Array
        (
            [id] => 85
            [parent_id] => 83
            [title] => Questionnaire three
        )

)

我想重新构建数组,以便子项在其父项下列出。例如:

I want to re-structure the array so child items are listed under their parents. For example:

Array
(
    [0] => Array
        (
            [id] => 83
            [parent_id] => 0
            [title] => Questionnaire one
        )

    [1] => Array
        (
            [id] => 85
            [parent_id] => 83
            [title] => Questionnaire three
        )

    [2] => Array
        (
            [id] => 84
            [parent_id] => 0
            [title] => Questionnaire two
        )
)

我已经搜索了先前的问题,但没有发现他们确实达到了上述要求。

I've searched previous questions but found none of them actually achieve the above.

有人可以帮我吗?

谢谢

推荐答案

您可以尝试

$array = Array(
        "0" => Array("id" => 83,"parent_id" => 0,"title" => "Questionnaire one"),
        "1" => Array("id" => 84,"parent_id" => 0,"title" => "Questionnaire two"),
        "2" => Array("id" => 85,"parent_id" => 83,"title" => "Questionnaire three"));

$id = array_map(function ($item) {return $item["id"];}, $array);
$parent = array_filter($array, function ($item){return $item['parent_id'] == 0;});
$lists = array();

foreach ($parent as $value)
{
    $lists[] = $value ;
    $children = array_filter($array, function ($item) use($value) {return $item['parent_id'] == $value['id'];});
    foreach($children as $kids)
    {
        $lists[]  = $kids ;
    }
}

echo "<pre>";
print_r($lists);

输出

Array
(
    [0] => Array
        (
            [id] => 83
            [parent_id] => 0
            [title] => Questionnaire one
        )

    [1] => Array
        (
            [id] => 85
            [parent_id] => 83
            [title] => Questionnaire three
        )

    [2] => Array
        (
            [id] => 84
            [parent_id] => 0
            [title] => Questionnaire two
        )

)

这篇关于根据父子关系重新构造数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆