Reputation: 3016
An array of associative arrays must be converted to an associative array whose keys are the values of one key of those associative arrays. For example, this array:
$source = array(array("key" => "a", "value" => "1"),
array("key" => "b", "value" => "2"),
array("key" => "a", "value" => "3"),
array("key" => "b", "value" => "4"));
must be converted to the following associative array, based on the values of the key "key":
$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")));
This is what I would do:
$dest = array();
foreach($source as $elem) {
$key = $elem["key"];
if(!array_key_exists($key, $dest)){
$dest[$key] = array();
}
array_push($dest[$key], $elem);
}
Is there a more idiomatic way?
Upvotes: 0
Views: 57
Reputation: 34914
Change your to this.
<?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);
?>
Check this : https://eval.in/605983
Output is :
Array
(
[a] => Array
(
[0] => Array
(
[key] => a
[value] => 1
)
[1] => Array
(
[key] => a
[value] => 3
)
)
[b] => Array
(
[0] => Array
(
[key] => b
[value] => 2
)
[1] => Array
(
[key] => b
[value] => 4
)
)
)
Upvotes: 0
Reputation: 3195
You can do it using simple foreach
stuff:
$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);
Upvotes: 1