In php, I have an indexed array of associative rows like this:
$the_array = [
['id' => 1, 'value' => 10, 'name' => 'apple'],
['id' => 1, 'value' => 20, 'name' => 'orange'],
['id' => 1, 'value' => 30, 'name' => 'banana'],
['id' => 2, 'value' => 100, 'name' => 'car'],
['id' => 2, 'value' => 200, 'name' => 'bicycle'],
];
and I would like to restructure it to by grouping on id
values and in each group I'd like to sum the value
values and make a comma-separated string of the name
values.
[
['id' => 1, 'value' => 60, 'name' => 'apple,orange,banana'],
['id' => 2, 'value' => 300, 'name' => 'car,bicycle']
]
This is what I tried:
function group_by($key, $data) {
$result = array();
foreach($data as $val) {
if(array_key_exists($key, $val)){
$result[$val[$key]][] = $val;
}else{
$result[""][] = $val;
}
}
return $result;
}
It's not working and the result is wrong/incomplete.
I would create an intermediary array which groups into array keys by
id
first, then use that to call combinations ofarray_column()
witharray_sum()
andimplode()
to produce your sumvalue
and combinedname
string.