2014-06-17 59 views
0

我有這樣的陣列,我想知道我怎麼能:如何計算由它們的發生和數量值在多維數組的元素在PHP

  1. 總數量如此finaly我只接收獨特產品的ID與他們qty- S,例如:

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

謝謝你在前進,

+0

使用[的foreach(HTTP://ch2.php。 net/manual/en/control-structures.foreach.php) – TiMESPLiNTER

+0

你是從數據庫中獲得這個數組嗎?否則,我建議你讓MySQL(或者你使用的任何數據庫引擎)用適當的查詢來解決它。 – Amjo

+0

不,這來自後 – thecore7

回答

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); 
+0

scragar我在這個$ productQuantities = [];爲什麼這是 – thecore7

+0

這將是你的PHP版本,我做了一個編輯。 – scragar

+0

好人! :) 謝謝 ! – thecore7

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]; 
    } 
} 

這時你會發現你在$緊湊

+0

簡單說一下,爲了同樣的目的'array_key_exists'大約比'isset'慢三倍,唯一能夠通過isset使用array_key_exists的地方就是值可以爲null的地方(在這種情況下永遠不可能)。 – scragar

相關問題