2014-06-17 2 views
0

나는이 배열을 가지고 내가 할 수있는 방법 궁금 해서요 :자신의 발생과 수량 값을 기준으로 PHP에서 다차원 배열의 요소를 계산하는 방법

  1. 합계 수량 그래서 마침내 내가 그들의 qty- 만의 고유 제품 ID를받을 S, 예를 들어

제품 805-1 조각 제품
1118-2 + 3 + 4 = 9pieces

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에서 결과를 찾을 수 있습니다. net/manual/en/control-structures.foreach.php) – TiMESPLiNTER

+0

데이터베이스에서이 어레이를 가져오고 있습니까? 그렇지 않으면, 당신은 MySQL (또는 당신이 사용하고있는 DB 엔진)이 적절한 쿼리로 그것을 해결하도록 권한다. – 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

당신이 시도해 볼 수도 있습니다, 사전에 감사합니다 //ch2.php :

$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'보다 약 3 배 느리다. isset을 통해 array_key_exists를 사용할 수있는 유일한 곳은 값이 null 일 수있는 곳이다. – scragar

관련 문제