PHP中数组的分组 [英] grouping of array in PHP

查看:45
本文介绍了PHP中数组的分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在PHP中有一个这样的编号数组

I have an numbered array like this in PHP

原始数组:

Array
        (
            [i] => Array
                (
                    [0] => Array
                        (
                            [id] => 1
                            [qty] => 5
                        )

                    [1] => Array
                        (
                            [id] => 2
                            [qty] => 5
                        )

                    [2] => Array
                        (
                            [id] => 2
                            [qty] => 5
                        )

                    [3] => Array
                        (
                            [id] => 1
                            [qty] => 5
                        )
                    [4] => Array
                        (
                            [id] => 3
                            [qty] => 5
                        )    
                )

        )

我希望它对相同的"id"进行分组,如果有重复项,则将数量加在一起.如果"id"是键而不是编号的键,我应该能够做到.

I want it to group the same "id" and add up quantity if there are duplicates, If the "id" is the key instead of numbered keys, I should be able to do it.

我期望的结果是:

Array
        (
            [i] => Array
                (
                    [0] => Array
                        (
                            [id] => 1
                            [qty] => 10
                        )

                    [1] => Array
                        (
                            [id] => 2
                            [qty] => 10
                        )

                    [2] => Array
                        (
                            [id] => 3
                            [qty] => 5
                        )    
                )

        )

推荐答案

工作解决方案

<?php 
$your_arr = array(
    array('id' => 1,'qty' => 5),
    array('id' => 2,'qty' => 5),
    array('id' => 2222,'qty' => 5),
    array('id' => 1,'qty' => 5),
    array('id' => 3,'qty' => 5)
);
$new = array();
foreach ($your_array as $r){
    if(!isset($new[$r['id']]))$t=0; //check the current id exist in $new if Not $t = 0; 
    else $t=$r['qty']; //if yes $t's value become the saved value in $new[$r['id']]
    $new[$r['id']]['id'] = $r['id'];
    $new[$r['id']]['qty'] = ($t+$r['qty']); // add the new value with $new[$r['id]]'s value.

}
echo "<pre>";print_r($new);
?>

这篇关于PHP中数组的分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆