欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

相同数组的组合为新数组

程序员文章站 2022-06-06 16:49:59
...
array (size=2)
  'id' => int 139
  'key' => string '11111' 

array (size=2)
  'id' => int 139
  'key' => string '22222' 

array (size=2)
  'id' => int 159
  'key' => string '33333'

array (size=2)
  'id' => int 159
  'key' => string '44444'

合并为

array (size=2)
  'id' => int 139
  'key' => string '11111,22222' 

array (size=2)
  'id' => int 159
  'key' => string '33333,44444'

回复内容:

array (size=2)
  'id' => int 139
  'key' => string '11111' 

array (size=2)
  'id' => int 139
  'key' => string '22222' 

array (size=2)
  'id' => int 159
  'key' => string '33333'

array (size=2)
  'id' => int 159
  'key' => string '44444'

合并为

array (size=2)
  'id' => int 139
  'key' => string '11111,22222' 

array (size=2)
  'id' => int 159
  'key' => string '33333,44444'

$arr = [
    ["id"=>139, "key"=>"111"],
    ["id"=>139, "key"=>"222"],
    ["id"=>159, "key"=>"333"],
    ["id"=>159, "key"=>"444"]
];

$res = [];
foreach( $arr as $item ) $res[ $item['id'] ][] = $item['key'];
相关标签: php