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"=> [""]
    ]
);

Php
Apr.28,2021

$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


clipboard.png

clipboard.png
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);
}
MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1eb2c25-481d7.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1eb2c25-481d7.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?