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

php中foreach的一个有关问题

程序员文章站 2022-06-03 16:42:20
...
php中foreach的一个问题

$list = array(
array('id' => 1, 'count' => 1),
array('id' => 1, 'count' => 2),
array('id' => 2, 'count' => 2),
array('id' => 3, 'count' => 3),
array('id' => 3, 'count' => 4)
);
$sort = array();
foreach($list as $v)
{
$sort[] = $v['id'];
}
$sort = array_unique($sort);
$new = array();
foreach($sort as $v1)
{
$c = 0;
foreach($list as $v2)
{
if($v1 == $v2['id'])
{
$c += $v2['count'];
}
}
$new[] = array('id' => $v1, 'count' => $c);
}

这是现在的做法,求简单更合理的做法!!
需求:现有的数组:$list,需要得到的结果:把数组内重复的id对应的字段count合并。如上面的结果数组$new


------解决思路----------------------

$list = array(
array('id' => 1, 'count' => 1),
array('id' => 1, 'count' => 2),
array('id' => 2, 'count' => 2),
array('id' => 3, 'count' => 3),
array('id' => 3, 'count' => 4)
);

// 執行計算操作
$tmp = array();

foreach($list as $val){
if(isset($tmp[$val['id']])){
$tmp[$val['id']] += $val['count'];
}else{
$tmp[$val['id']] = $val['count'];
}
}

ksort($tmp); // 按key排序

$new = array();
foreach($tmp as $k=>$v){
array_push($new,array('id'=>$k,'count'=>$v));
}

print_r($new);

------解决思路----------------------
$list = array(
array('id' => 1, 'count' => 1),
array('id' => 1, 'count' => 2),
array('id' => 2, 'count' => 2),
array('id' => 3, 'count' => 3),
array('id' => 3, 'count' => 4)
);
$new = array();
foreach($list as $r) {
if(! isset($new[$r['id']])) $new[$r['id']] = $r;
else $new[$r['id']]['count'] += $r['count'];
}
$new = array_values($new);
print_r($new);
Array
(
[0] => Array
(
[id] => 1
[count] => 3
)

[1] => Array
(
[id] => 2
[count] => 2
)

[2] => Array
(
[id] => 3
[count] => 7
)

)
php中foreach的一个有关问题

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。

相关文章

相关视频