php数组整合

WBOY
Release: 2016-06-06 20:25:18
Original
1151 people have browsed it

<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>
Copy after login
Copy after login

回复内容:

<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>
Copy after login
Copy after login

<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>
Copy after login
Related labels:
php
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template