具有相同键值的多个数组合并为一个数组

时间:2018-12-27 06:58:01

标签: php arrays multidimensional-array foreach array-merge

我面临多重数组计算的问题。我正在使用数据库mysql,操作语言是PHP。当我从数据库结果中获取结果时,显示具有固定键和值的多个数组。当一个阵列键码值与单独的阵列键码值相同时,该阵列将合计为总数量和价格。这是从数据库中获取结果。

['code'=>'aaa','name'=>'a','qty'=>20,'price'=>12.00],
['code'=>'bbb','name'=>'b','qty'=>20,'price'=>12.00],
['code'=>'ccc','name'=>'c','qty'=>20,'price'=>12.00],
['code'=>'aaa','name'=>'a','qty'=>20,'price'=>12.00],
['code'=>'ddd','name'=>'d','qty'=>20,'price'=>12.00],
['code'=>'ccc','name'=>'c','qty'=>5,'price'=>8.00],
['code'=>'bbb','name'=>'b','qty'=>15,'price'=>10.00],
['code'=>'ggg','name'=>'g','qty'=>20,'price'=>12.00],

并且我想将此结果自定义为这种格式。

['code'=>'aaa','name'=>'a','qty'=>40,'price'=>24.00],
['code'=>'bbb','name'=>'b','qty'=>35,'price'=>22.00],
['code'=>'ccc','name'=>'c','qty'=>25,'price'=>20.00],
['code'=>'ddd','name'=>'d','qty'=>20,'price'=>12.00],
['code'=>'ggg','name'=>'g','qty'=>20,'price'=>12.00],

请帮助我解决此问题。我做了很多尝试,但没有任何解决方法。

4 个答案:

答案 0 :(得分:3)

您可以使用array_reduce为您提供所需的结果。匿名回调检查结果数组中是否存在当前值中的代码,如果存在,则对当前数量和价格求和。如果不是,则将当前值推入结果数组。代码使用原始数组中的第一个值初始化结果,这样我们就不必担心未定义的索引:

$newdata = array_reduce(array_slice($data, 1),
    function ($c, $v) { 
        if (($k = array_search($v['code'], array_column($c, 'code'))) !== false) {
            $c[$k]['qty'] += $v['qty'];
            $c[$k]['price'] += $v['price'];
        }
        else {
            $c[] = $v;
        }
        return $c;
    }, array($data[0]));
print_r($newdata);

输出:

Array (
    [0] => Array ( [code] => aaa [name] => a [qty] => 40 [price] => 24 )
    [1] => Array ( [code] => bbb [name] => b [qty] => 35 [price] => 22 )
    [2] => Array ( [code] => ccc [name] => c [qty] => 25 [price] => 20 )
    [3] => Array ( [code] => ddd [name] => d [qty] => 20 [price] => 12 )
    [4] => Array ( [code] => ggg [name] => g [qty] => 20 [price] => 12 ) 
)

Demo on 3v4l.org

答案 1 :(得分:2)

您可以通过一维数组来实现...

$newArray = array();   //create new array..

foreach($array as $item) {
    if(isset($newArray[$item['code']])) { //if already exist then sum of qty and price...
        $newArray[$item['code']]['qty'] += $newArray[$item['code']]['qty'];
        $newArray[$item['code']]['price'] += $newArray[$item['code']]['price'];
    }else {   //if first time then add array into them...
        $newArray[$item['code']] = $item;
    }
}

通过使用查询,您可以这样做

SELECT code, name, SUM(qty), SUM(price) 
from tableName 
group by code

答案 2 :(得分:0)

SELECT code, name, SUM(qty), price 
from your_table_name 
group by name

在使用mysql提取结果时使用group by。希望这会有所帮助。

答案 3 :(得分:0)

尝试这个

PHP Warning:  file_get_contents(): SSL operation failed with code 1. OpenSSL Error messages:
error:1416F086:SSL routines:tls_process_server_certificate:certificate verify failed in /t.php on line 1