Re-structure array based on parent/child relationship

别等时光非礼了梦想. 提交于 2019-12-24 15:21:56

问题


I have the following array structure:

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.

Can someone please help me with this?

Thanks


回答1:


You can try

$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);

Output

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
        )

)



回答2:


You could use uksort(). Heres a DEMO.

function cmp($a, $b) {
  if ($stock[$a] != $stock[$b]) return $stock[$b] - $stock[$a];
  return strcmp($a, $b);
}

$a = array(5 => 'apple', 1 => 'banana', 6 => 'orange', 2 => 'kiwi');

uksort($a, "cmp");

foreach ($a as $key => $value) {
   echo "$key: $value\n";
}


来源:https://stackoverflow.com/questions/12960943/re-structure-array-based-on-parent-child-relationship

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!