必须将关联数组数组转换为关联数组,其关键字是这些关联数组的一个键的值。例如,这个数组:
$source = array(array("key" => "a", "value" => "1"),
array("key" => "b", "value" => "2"),
array("key" => "a", "value" => "3"),
array("key" => "b", "value" => "4"));
必须根据键"键" 的值转换为以下关联数组:
$dest = array("a" => array(array("key" => "a", "value" => "1"),
array("key" => "a", "value" => "3")),
"b" => array(array("key" => "b", "value" => "2"),
array("key" => "b", "value" => "4")));
这就是我要做的事情:
$dest = array();
foreach($source as $elem) {
$key = $elem["key"];
if(!array_key_exists($key, $dest)){
$dest[$key] = array();
}
array_push($dest[$key], $elem);
}
是否有更惯用的方式?
答案 0 :(得分:1)
您可以使用简单的foreach
内容:
$source_arr = array(array("key" => "a", "value" => "1"),
array("key" => "b", "value" => "2"),
array("key" => "a", "value" => "3"),
array("key" => "b", "value" => "4"));
$destination_arr = array();
foreach ($destination_arr as $k => $v)
{
$key = $v['key'];
$destination_arr[$key][$k] = array('key' => $v['key'], 'value' => $v['value']);
}
print_r($destination_arr);
答案 1 :(得分:0)
将您改为此。
Box<Option<Foo>>
输出是:
<?php
$dest = array(array("key" => "a", "value" => "1"),
array("key" => "b", "value" => "2"),
array("key" => "a", "value" => "3"),
array("key" => "b", "value" => "4"));
$result = array();
foreach($dest as $elem) {
$result[$elem['key']][] = ["key"=>$elem['key'],"value"=>$elem['value']];
}
print_r($result);
?>