如何计算php中多维数组中元素的出现次数和数量值

时间:2014-06-17 12:02:03

标签: php arrays multidimensional-array

我有这个阵列,我想知道我怎么能:

  1. 总结数量如此最终我只收到了他们的qty-s的唯一产品ID,例如:
  2. 产品805 - 1件
        产品1118 - 2 + 3 + 4 = 9件

    array(2){
        ["product"]=> array(4){    
            [0]=> string(3) "805"     
            [1]=> string(4) "1118"     
            [2]=> string(4) "1118"     
            [3]=> string(4) "1118"     
        }     
        ["qty"]=> array(4) {      
            [0]=> string(1) "1"         
            [1]=> string(1) "2"     
            [2]=> string(1) "3"     
            [3]=> string(1) "4"     
        }    
    }    
    

    提前谢谢你,

2 个答案:

答案 0 :(得分:1)

$productQuantities = array();
$products = array("805","1118","1118","1118");
$quantities = array(1,2,3,4);
foreach($products AS $key=>$productId){
    $quantity = (int) $quantities[$key];
    if(isset($productQuantities[$productId])){
        $productQuantities[$productId] += $quantity;
    } else {
        $productQuantities[$productId] = $quantity;
    }
}

var_dump($productQuantities);

答案 1 :(得分:0)

你可以试试这个:

$zipped=array_map(
    null, 
    $your_array['product'], 
    $your_array['qty']
);

$compact = array();

foreach ($zipped as $k => $v){

    if(!array_key_exists($v[0], $compact)){
        $compact[$v[0]] = $v[1];
    } else {
        $compact[$v[0]] += $v[1];
    }
}

然后你会在$ compact

中找到你的结果