Home > Backend Development > PHP Tutorial > thinkphp二维数组怎么去除重复并将重复值相加

thinkphp二维数组怎么去除重复并将重复值相加

PHPz
Release: 2020-09-04 17:22:38
Original
2749 people have browsed it

thinkphp二维数组去除重复并将重复值相加的方法:首先创建一个PHP文件;然后通过“foreach”语句对指定二维数组进行遍历;最后使用迭代器去除重复并将重复值相加即可。

thinkphp二维数组怎么去除重复并将重复值相加

thinkphp二维数组怎么去除重复并将重复值相加?

问题:

$arr = array(
    array('id' => 123, 'name' => '张三', 'amount'=>'1'),
    array('id' => 123, 'name' => '李四', 'amount' => '1'),
    array('id' => 124, 'name' => '王五', 'amount' => '1'),
    array('id' => 125, 'name' => '赵六', 'amount' => '1'),
    array('id' => 126, 'name' => '赵六', 'amount' => '2'),
    array('id' => 126, 'name' => '赵六', 'amount' => '2')
);
Copy after login

如果数组内的name相等,最终保留一个,但是amount的值相加。

处理方法:

对数组进行一次遍历就可以了。

$arr = array(
    array('id' => 123, 'name' => '张三', 'amount'=>'1'),
    array('id' => 123, 'name' => '李四', 'amount' => '1'),
    array('id' => 124, 'name' => '王五', 'amount' => '1'),
    array('id' => 125, 'name' => '赵六', 'amount' => '1'),
    array('id' => 126, 'name' => '赵六', 'amount' => '2'),
    array('id' => 126, 'name' => '赵六', 'amount' => '2')
);
 
$new = array();
 
foreach($arr as $row){
    if(isset($new[$row['name']])){
        $new[$row['name']]['amount'] += $row['amount'];
    }else{
        $new[$row['name']] = $row;
    }
}
 
print_r($new);
Copy after login

使用迭代器即可,非常方便。

更多相关技术知识,请访问PHP中文网

Related labels:
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