我有一个像这样的二维数组:
$array = [
[..., "key"=>"key 1",...],
[..., "key"=>"key 2",...],
[..., "key"=>"key 2",...],
[..., "key"=>"key 3",...],
[..., "key"=>"key 3",...],
[..., "key"=>"key 3",...],
];
我要从此数组中获得三维数组,并用相同的“键”值拆分,
像这样:
$array_output = [
[
[..., "key"=>"key 1",...],
],
[
[..., "key"=>"key 2",...],
[..., "key"=>"key 2",...],
],
[
[..., "key"=>"key 3",...],
[..., "key"=>"key 3",...],
[..., "key"=>"key 3",...],
],
];
答案 0 :(得分:1)
您可以使用array-reduce进行操作。考虑以下示例:
$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
中的键顺序不相关。
答案 1 :(得分:0)
最后,此功能符合我的期望:
protoc
但是,它返回键值对,例如:
mv protobuf/protoc-artifacts/target/linux/x86_64/protoc.exe protobuf/protoc-artifacts/target/linux/x86_64/protoc
但这对我来说没有问题:)