在php中用给定的键对值求和?[重复]

oaxa6hgo  于 2023-04-19  发布在  PHP
关注(0)|答案(2)|浏览(122)

此问题已在此处有答案

Group 2d array's row data by one column and sum another column within each group to produce a reduced 2d array(3个答案)
7个月前关闭。
给定这个数组:

array(40) {
  [0]=>
  array(10) {
    ["item"]=>
    string(5) "AABBCC"
    ["quants"]=>
    string(1) "1"
  }
  [1]=>
  array(10) {
    ["item"]=>
    string(5) "AABBCC"
    ["quants"]=>
    string(1) "1"
  }  
  [2]=>
  array(10) {
    ["item"]=>
    string(5) "SLF02"
    ["quants"]=>
    string(1) "1"

  }
  [3]=>
  array(10) {
    ["item"]=>
    string(5) "SLF02"
    ["quants"]=>
    string(1) "3"
  }
}

如果不使用foreach,我最终会得到这样的输出:

array(40) {
    [0]=>
    array(10) {
      ["item"]=>
      string(5) "AABBCC"
      ["quants"]=>
      string(1) "2"
    }
    [1]=>
    array(10) {
      ["item"]=>
      string(5) "SLF02"
      ["quants"]=>
      string(1) "3"
    }  
  }

在php中有没有array_sum函数来处理像这样的多维数组?

u0sqgete

u0sqgete1#

这是一个坏主意,但似乎是一个有趣的挑战,没有foreach:

$arr = 
[
  [
    "item" =>"AABBCC",
    "quants" => "1",
  ],
  [
    "item" => "AABBCC", 
    "quants" => "1",
  ],
  [
    "item" => "SLF02", 
    "quants" => "1",
  ],
  [
    "item" => "SLF02", 
    "quants" => "3",
  ]
];

$arr = array_values(call_user_func_array("array_merge", array_map(function($i) use ($arr) {
  return [$i["item"] => ["item" => $i["item"], "quants" => array_reduce(
    array_filter($arr, function($j) use ($i) {
        return $j["item"] == $i["item"]; 
    }), function($carry, $item) { 
        return $carry + $item["quants"]; 
    })
  ]];
}, $arr)));

var_dump($arr);

/*
array(2) {
  [0]=>
  array(2) {
    ["item"]=>
    string(6) "AABBCC"
    ["quants"]=>
    int(2)
  }
  [1]=>
  array(2) {
    ["item"]=>
    string(5) "SLF02"
    ["quants"]=>
    int(4)
  }
}
*/
smtd7mpg

smtd7mpg2#

以下是我的方法:

<?php
$array = array(
    array('item'=>'AABBCC','quants'=>1),
    array('item'=>'AABBCC','quants'=>1),
    array('item'=>'SLF02','quants'=>1),
    array('item'=>'SLF02','quants'=>3),
);

$summed_array = array();

foreach($array as $row){
    $key = $row['item'];

    if(!isset($summed_array[$key])){
        $summed_array[$key] = array(
            'item' => $row['item'],
            'quants' => 0
        );
    }

    $summed_array[$key]['quants'] += $row['quants'];
}

// turn the array back to a 0 based array
$summed_array = array_values($summed_array);

echo '<pre>',print_r($summed_array),'</pre>';

相关问题