用PHP中的给定键值和值?

时间:2015-10-23 21:28:34

标签: php

给出这个数组:

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"
    }  
  }

是否有任何array_sum函数用这样的多维数组在php中执行此操作?

2 个答案:

答案 0 :(得分:2)

这是一个糟糕的主意,但如果没有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)
  }
}
*/

答案 1 :(得分:1)

这是我的方法:

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