Home  >  Article  >  Backend Development  >  php中foreach的一个有关问题

php中foreach的一个有关问题

WBOY
WBOYOriginal
2016-06-13 12:18:081038browse

php中foreach的一个问题

<br />$list = array(<br />            array('id' => 1, 'count' => 1),<br />            array('id' => 1, 'count' => 2),<br />            array('id' => 2, 'count' => 2),<br />            array('id' => 3, 'count' => 3),<br />            array('id' => 3, 'count' => 4)<br />        );<br />        $sort = array();<br />        foreach($list as $v)<br />        {<br />            $sort[] = $v['id'];<br />        }<br />        $sort = array_unique($sort);<br />        $new = array();<br />        foreach($sort as $v1)<br />        {<br />            $c = 0;<br />            foreach($list as $v2)<br />            {<br />                if($v1 == $v2['id'])<br />                {<br />                    $c += $v2['count'];<br />                }<br />            }<br />            $new[] = array('id' => $v1, 'count' => $c);<br />        }<br /><br />这是现在的做法,求简单更合理的做法!!<br />需求:现有的数组:$list,需要得到的结果:把数组内重复的id对应的字段count合并。如上面的结果数组$new<br />


------解决思路----------------------
<br />$list = array(<br />            array('id' => 1, 'count' => 1),<br />            array('id' => 1, 'count' => 2),<br />            array('id' => 2, 'count' => 2),<br />            array('id' => 3, 'count' => 3),<br />            array('id' => 3, 'count' => 4)<br />        );<br /><br />// 執行計算操作<br />$tmp = array();<br /><br />foreach($list as $val){<br />    if(isset($tmp[$val['id']])){<br />        $tmp[$val['id']] += $val['count'];<br />    }else{<br />        $tmp[$val['id']] = $val['count'];<br />    }<br />}<br /><br />ksort($tmp); // 按key排序<br /><br />$new = array();<br />foreach($tmp as $k=>$v){<br />    array_push($new,array('id'=>$k,'count'=>$v));<br />}<br /><br />print_r($new);<br />

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

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn