简体   繁体   中英

How to increment values which having same array element in php?

I am having following array and i want to increment quantity if date are same.

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 )
             )

please explain me how to do such thing in php.

you can use array_search(); built in function in some way

a simple example:

<?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;
?>

You can use this logic for above task.

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]);
            }
        }
    }

Try this way simply using 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);

OR Using 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM