数组和元素的值相同?

时间:2015-09-14 21:34:47

标签: php

如何对数组的元素值进行求和?

$arr = [
   ['id' => 1, 'qty' => 100, 'name' => 'a'],
   ['id' => 1, 'qty' => 100, 'name' => 'a'],
   ['id' => 2, 'qty' => 100, 'name' => 'b']
];

成为:

$arr = [
   ['id' => 1, 'qty' => 200, 'name' => 'a'],
   ['id' => 2, 'qty' => 100, 'name' => 'b']
];

我试过但是回来了

  

[ 1=>['qty'=>200], 2=>['qty'=>100] ]

我试过但是回来了

for($i=0; $i<count($cok);$i++){
        $item_id = $cok[$i]['id'];
        $quantity = $cok[$i]['quantity'];
        if (isset($new_items[$item_id])) {
            $new_items[$item_id] = ['quantity' => $new_items[$item_id]['quantity'] + $quantity];
        } else {
            $new_items[$item_id] = ['quantity' => $quantity];
        }
    }

2 个答案:

答案 0 :(得分:0)

潜入我的viper

and inplace snippet,确切地返回您需要的内容:

<?
$arr = array(
    array('id' => 1, 'qty' => 100, 'name' => 'a'),
    array('id' => 1, 'qty' => 100, 'name' => 'a'),
    array('id' => 2, 'qty' => 100, 'name' => 'b')
);

$ids = array();
foreach ($arr as $i => $subarray) {
    if (!($remove_from_array = array_key_exists($subarray['id'], $ids))) {
        $ids[$subarray['id']] = 0;
    }
    $ids[$subarray['id']] += $subarray['qty'];
    if ($remove_from_array) {
        unset($arr[$i]);
    }
}
foreach ($arr as &$subarray) {
    $subarray['qty'] = $ids[$subarray['id']];
}

print_r($arr);

答案 1 :(得分:0)

简单如馅饼(:

<?php
$arr = array(
    array('id' => 1, 'qty' => 100, 'name' => 'a'),
    array('id' => 1, 'qty' => 100, 'name' => 'a'),
    array('id' => 2, 'qty' => 100, 'name' => 'b')
);

$new_arr = array();
foreach($arr AS $item) {
  if(isset($new_arr[$item['id']])) {
    $new_arr[$item['id']]['qty'] += $item['qty'];
    continue;
  }

  $new_arr[$item['id']] = $item;
}

$arr = array_values($new_arr);

var_dump($arr);