按键=>值分割PHP数组 [英] Split PHP Array by Key=>Value
本文介绍了按键=>值分割PHP数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个像这样的二维数组:
I have a two dimensional array like this:
$array = [
[..., "key"=>"key 1",...],
[..., "key"=>"key 2",...],
[..., "key"=>"key 2",...],
[..., "key"=>"key 3",...],
[..., "key"=>"key 3",...],
[..., "key"=>"key 3",...],
];
我希望从该数组中获得一个三维数组,并用相同的键"值拆分,
像这样:
I want a three dimensional array from this array, splitted by the same "key" value,
like this:
$array_output = [
[
[..., "key"=>"key 1",...],
],
[
[..., "key"=>"key 2",...],
[..., "key"=>"key 2",...],
],
[
[..., "key"=>"key 3",...],
[..., "key"=>"key 3",...],
[..., "key"=>"key 3",...],
],
];
推荐答案
You can do that with array-reduce. Consider this example:
$arr = [];
$arr[] = array("key" => "key1", "v" => "a");
$arr[] = array("key" => "key2", "v" => "b");
$arr[] = array("key" => "key3", "v" => "c");
$arr[] = array("key" => "key2", "v" => "d");
$arr[] = array("key" => "key2", "v" => "e");
function reduceByKey($carry, $item) {
$carry[$item["key"]][] = $item;
return $carry;
}
$res = array_values(array_reduce($arr, "reduceByKey",[]));
现在 $ res
将显示您的输出.请注意, $ arr
中的键顺序不相关.
Now $res
will have your output. Notice that the order of the keys in $arr
in not relevant.
这篇关于按键=>值分割PHP数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文