PHP拆分和组数组

时间:2018-03-04 21:45:22

标签: php arrays key key-value

我很难搞清楚如何修改我的数组。原始阵列就是这个......

$array = array(
array(
    "fruit" => "pineapple",
    "id" => "aaa",
),
array(
    "fruit" => "orange",
    "id" => "aaa",
),
array(
    "fruit" => "apple",
    "id" => "bbb",
),
array(
    "fruit" => "pear",
    "id" => "bbb",
),
array(
    "fruit" => "peach",
    "id" => "ccc",
),
array(
    "fruit" => "melon",
    "id" => "ccc",
)
);

我需要通过id将此数组转换为键数组。例如,我希望最终结果看起来像这样......

$array = array(
"aaa" => array("pineapple", "orange"),
"bbb" => array("apple", "pear"),
"ccc" => array("peach", "melon"),
);

我试图遍历数组并提取我需要的东西并重建数组但我无法弄明白。希望有人可以帮助我。谢谢!

1 个答案:

答案 0 :(得分:2)

你可以通过这种方式创建一个新数组:

$array = array(
    array(
        "fruit" => "pineapple",
        "id" => "aaa",
    ),
    array(
        "fruit" => "orange",
        "id" => "aaa",
    ),
    array(
        "fruit" => "apple",
        "id" => "bbb",
    ),
    array(
        "fruit" => "pear",
        "id" => "bbb",
    ),
    array(
        "fruit" => "peach",
        "id" => "ccc",
    ),
    array(
        "fruit" => "melon",
        "id" => "ccc",
    )
);

// empty array
$result = [];

// loop trough data
foreach($array as $value){

    // add item to the $result array. Then make the id the key and the fruit the value
    $result[$value['id']][] = $value['fruit'];

}

//print array
print_r($result);

结果将是

Array ( [aaa] => Array ( [0] => pineapple [1] => orange ) [bbb] => Array ( [0] => apple [1] => pear ) [ccc] => Array ( [0] => peach [1] => melon ) )