如何增加php中具有相同数组元素的值?

时间:2016-01-30 06:14:58

标签: php arrays

我有以下数组,如果日期相同,我想增加数量。

Array ( 
                [0] => Array ( [date] => 2016-02-02 [quantity] => 2 ) 
                [1] => Array ( [date] => 2016-02-04 [quantity] => 1 ) 
                [2] => Array ( [date] => 2016-02-05 [quantity] => 1 )
                [3] => Array ( [date] => 2016-02-02 [quantity] => 1 ) 
                [4] => Array ( [date] => 2016-02-03 [quantity] => 1 )
                [5] => Array ( [date] => 2016-02-02 [quantity] => 2 ) 
                [6] => Array ( [date] => 2016-02-03 [quantity] => 2 ) 
                [7] => Array ( [date] => 2016-02-04 [quantity] => 2 )
      ) 
  for example if 0 index having date 2016-02-02 and quantity 2,and same like 3rd index having same date but different quantity like wise 5th index. Now i want to add only the quantity if date are same and store into new array as

Array ( 
            [0] => Array ( [date] => 2016-02-02 [quantity] => 5 ) 
            [1] => Array ( [date] => 2016-02-04 [quantity] => 3 ) 
            [2] => Array ( [date] => 2016-02-05 [quantity] => 1 )
            [4] => Array ( [date] => 2016-02-03 [quantity] => 3 )
             )
请告诉我如何在php中做这样的事情。

3 个答案:

答案 0 :(得分:0)

您可以以某种方式使用array_search();内置功能

一个简单的例子:

<?php
$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');

$key = array_search('green', $array); // $key = 2;
$key = array_search('red', $array);   // $key = 1;
?>

答案 1 :(得分:0)

您可以将此逻辑用于上述任务。

foreach($arrayname as $key=>$value)
    {
        foreach($arrayname as $key1=>$value1)
        {
            if($value['date']==$value1['date']&&$key!=$key1)
            {
                $value['quantity']=$value['quantity']+$value1['quantity'];
                unset($arrayname[$key]);
            }
        }
    }

答案 2 :(得分:0)

只需使用foreach

即可
$sum = array();

foreach ($array as $item) {
    if (!isset($sum[$item['date']])) $sum[$item['date']] = 0;
    $sum[$item['date']] += $item['quantity'];
}

 print '<pre>';
 print_r($sum);

   使用array_reduce()

$sum = array_reduce($array, function($result, $item) {
    if (!isset($result[$item['date']])) $result[$item['date']] = 0;
    $result[$item['date']] += $item['quantity'];
    return $result;
}, array());

    print '<pre>';
    print_r($sum);