1

私は次の配列構造を持っています:

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

以前の質問を検索しましたが、実際に上記を達成しているものはありませんでした。

誰かがこれを手伝ってくれませんか?

ありがとう

4

2 に答える 2

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
        )

)
于 2012-10-18T18:32:44.430 に答える
1

uksort()を使用できます。デモがあります

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";
}
于 2012-10-18T18:16:07.047 に答える