首頁 >後端開發 >php教程 >php数组整合

php数组整合

WBOY
WBOY原創
2016-06-06 20:25:181163瀏覽

<code class="php"> $arr=[
     ['id'=>1,'name'=>'php','num'=>3],
     ['id'=>2,'name'=>'js','num'=>1],
     ['id'=>1,'name'=>'php','num'=>2],
     ['id'=>3,'name'=>'python','num'=>2],
 ];
//怎么对id相同的对num求和并去重,返回的结果为
 $arr=[
     ['id'=>1,'name'=>'php','num'=>5],
     ['id'=>2,'name'=>'js','num'=>1],
     ['id'=>3,'name'=>'python','num'=>2],
 ];</code>

回复内容:

<code class="php"> $arr=[
     ['id'=>1,'name'=>'php','num'=>3],
     ['id'=>2,'name'=>'js','num'=>1],
     ['id'=>1,'name'=>'php','num'=>2],
     ['id'=>3,'name'=>'python','num'=>2],
 ];
//怎么对id相同的对num求和并去重,返回的结果为
 $arr=[
     ['id'=>1,'name'=>'php','num'=>5],
     ['id'=>2,'name'=>'js','num'=>1],
     ['id'=>3,'name'=>'python','num'=>2],
 ];</code>

<code>$result = [];
foreach ($arr as $v) {
    if (isset($result[$v['id']])) {
        $result[$v['id']]['num'] += $v['num'];
    }
    else {
        $result[$v['id']] = $v;
    }
}
print_r($result);</code>
陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn