你好,所以这是我的数组:
[0] => Array
(
[id] => 10
[count] => 10
)
[1] => Array
(
[id] => 10
[count] => 20
)
[2] => Array
(
[id] => 10
[count] => 30
)
我想通过id将这3个数组合并为1格式: 数组(id =>' 10',count =>(' 10',' 20',' 30')) 我有多个ID,每个我想返回一个字符串,其格式为#34; 10,20,30等。"有什么想法吗?
答案 0 :(得分:0)
没有搜索我会尝试这样的
foreach($source as $s){
$dest[$s['id']]['count'][] = $s['count'];
}
之后你可以通过implode(',', $array);
答案 1 :(得分:0)
如果U强制执行,你可以这样做:
<?php
$source = [
[
'id' => 10,
'count' => 1,
],
[
'id' => 15,
'count' => 2,
],
[
'id' => 10,
'count' => 3,
],
[
'id' => 12,
'count' => 4,
],
[
'id' => 10,
'count' => 5,
],
];
$output = [];
foreach($source as $arr) {
if (!isset($output[$arr['id']])) $output[$arr['id']] = '';
$output[$arr['id']] .= $arr['count'].',';
}
var_dump($output);
这里唯一的事情是最后还有一个额外的,
。
running example
答案 2 :(得分:0)
这将完全返回所请求的数组(id =&gt;'10',count =&gt;('10','20','30'))
foreach($array as $x){
$newarray[$x["id"]][]=$x["count"];
}
foreach($newarray as $id=>$count){
$c=implode(",",$count);
$newnewarray[]=array("id"=>$id,"count"=>"($c)");
}
print_r($newnewarray);
答案 3 :(得分:0)
这是没有尾随的代码,
$result = array();
foreach($source as $s){
if(!isset($result[$s['id']]))
$result[$s['id']] = $s['count'];
else
$result[$s['id']] .= ',' . $s['count'];
}
var_dump($result);