如何合并两个数组并求和

时间:2018-08-15 13:29:57

标签: php arrays multidimensional-array

这是我的阵列

array(5) {
    [0]=>
        array(3) {
        ["product"]=>
        string(14) "apple"
        ["quantity"]=>
        int(1)
        ["color"]=>
        string(5) "red"
    }
    [1]=>
        array(3) {
        ["quantity"]=>
        int(1)
        ["color"]=>
        string(6) "red"
        ["product"]=>
        string(17) "berry"
    }
    [2]=>
        array(3) {
        ["quantity"]=>
        int(5)
        ["color"]=>
        string(6) "green"
        ["product"]=>
        string(14) "apple"
    }
    [3]=>
        array(3) {
        ["quantity"]=>
        int(5)
        ["color"]=>
        string(6) "red"
        ["product"]=>
        string(14) "apple"
    }
    [4]=>
        array(3) {
        ["quantity"]=>
        int(4)
        ["color"]=>
        string(5) "red"
        ["product"]=>
        string(14) "apple"
    }
}

如果它们是样品产品且数量相同,我想对数量求和。 红苹果x 1和红苹果x 4和红苹果x 5将合并为红苹果x 10,但绿苹果将保留。

我该怎么做?

3 个答案:

答案 0 :(得分:2)

您可以使用array_reduce合并这些数据。

$data = [
    ['product' => 'apple', 'color' => 'red',   'quantity' => 1],
    ['product' => 'berry', 'color' => 'red',   'quantity' => 1],
    ['product' => 'apple', 'color' => 'green', 'quantity' => 5],
    ['product' => 'apple', 'color' => 'red',   'quantity' => 5],
    ['product' => 'apple', 'color' => 'red',   'quantity' => 4],
];

$result = array_values(array_reduce($data, function($map, $item) {
    $key = "{$item['product']}_{$item['color']}";
    if (!isset($map[$key])) { // first occurence
        $map[$key] = $item;
    } else { // next occurence - just increment quantity 
        $map[$key]['quantity'] += $item['quantity'];
    }
    return $map;
}, []));

foreach ($result as $item) echo json_encode($item), PHP_EOL;
{"product":"apple","color":"red","quantity":10}
{"product":"berry","color":"red","quantity":1}
{"product":"apple","color":"green","quantity":5}

答案 1 :(得分:0)

假设您的产品位于$products之类的数组中

$products = array( array('quantity' => 5, 'color' => 'red', 'product' => 'apple'), .. );
$summed = array();
for($i=0,$count=count($products);$i<$count;$i++) 
    if (!isset($summed[$products[$i]['product'].$products[$i]['color']])) {
        $summed[$products[$i]['product'].$products[$i]['color']] = $products[$i];
    } else $summed[$products[$i]['product'].$products[$i]['color']]['quantity'] += $products[$i]['quantity'];

现在$summed已准备好所有产品。您可以使用array_values放弃键,也可以继续使用它。

答案 2 :(得分:-3)

var $ret  = array();
foreach ($array as $value){
  foreach ($ret as &$v){
      if ($value['color'] == $v['color'] && $value['product'] == $v['product']){
          $v['quantity'] += $value['quantity'];
          $i = true;
      }
  }
   if(!$i){
      array_push($ret,$value);
  }
  unset($i);
}