PHPでは、次のような連想行のインデックス付き配列があります。
$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'],
];
値をグループ化して再構築し、各グループで値を合計して値のコンマ区切りの文字列を作成しid
たいと思います。value
name
[
['id' => 1, 'value' => 60, 'name' => 'apple,orange,banana'],
['id' => 2, 'value' => 300, 'name' => 'car,bicycle']
]
これは私が試したものです:
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;
}
機能しておらず、結果が間違っている/不完全です。