根据父/子关系重新构造数组

时间:2012-10-18 18:07:10

标签: php arrays parent relationship

我有以下数组结构:

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
        )

)

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

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 个答案:

答案 0 :(得分:2)

你可以尝试

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

)

答案 1 :(得分:1)

您可以使用uksort()。继承人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";
}