PHP operation array problem
<?php
//////
$redata = array(
0=>["id"=>1,"name"=>"","age"=>22,"hobby"=>""],
1=>["id"=>1,"name"=>"","age"=>22,"hobby"=>""],
2=>["id"=>2,"name"=>"","age"=>20,"hobby"=>""],
);
//
$arr = array(
0=>[
"id"=>1,"name"=>"","age"=>22,"hobby"=> ["", ""]
],
1=>[
"id"=>2,"name"=>"","age"=>20,"hobby"=> [""]
]
);
$redata = array(
0 => ['id' => 1, 'name' => '', 'age' => 22, 'hobby' => ''],
1 => ['id' => 1, 'name' => '', 'age' => 22, 'hobby' => ''],
2 => ['id' => 2, 'name' => '', 'age' => 20, 'hobby' => ''],
);
$result = array_reduce($redata, function ($arr, $item) {
$key = array_search($item['id'], array_column($arr, 'id'));
if ($key === false) {
$item['hobby'] = [$item['hobby']];
$arr[] = $item;
} else {
$arr[$key]['hobby'][] = $item['hobby'];
}
return $arr;
}, []);
var_dump($result);
$arr = [];
foreach($redata as $k=>$row){
foreach($row as $key => $item){
if($key === 'hobby'){
$arr[$row['id']][$key][] = $item;
}else{
$arr[$row['id']][$key] = $item;
}
}
}
var_dump($arr);
$arr = [];
foreach($redata as $v){
$arr[$v['id']]['id'] = $v['id'];
$arr[$v['id']]['name'] = $v['name'];
$arr[$v['id']]['age'] = $v['age'];
$arr[$v['id']]['hobby'][] = $v['hobby'];
}
$idMap = array_column($arr,'id');
array_multisort($arr,SORT_ASC,$idMap);
var_dump($arr);
if the array field is fixed, omit if
judgment time
Code
`
$redata = array (
)
0=>['id'=>1,'name'=>'','age'=>22,'hobby'=>''],
1=>['id'=>1,'name'=>'','age'=>22,'hobby'=>''],
2=>['id'=>2,'name'=>'','age'=>20,'hobby'=>''],
);
function hebing ($redata) {
foreach ($redata as $k => $v) {
if($redata[$k]['id']==$redata[$k+1]['id']){
$redata[$k+1]['hobby'] = [$redata[$k]['hobby'],$redata[$k+1]['hobby']];
array_splice($redata, $k, 1);
}
}
return $redata;
}
var_dump (hebing ($redata));
`
A foreach is easy to understand.
function hobby_merge($redata)
{
$result = [];
foreach($redata as $item) {
if (!isset($result[$item['id']])) {
$item['hobby'] = (array) $item['hobby'];
$result[$item['id']] = $item;
continue;
}
$result[$item['id']]['hobby'][] = $item['hobby'];
}
return array_values($result);
}