计算不同单位的关联数组

时间:2015-11-21 18:53:42

标签: php associative-array

我试图将某个危险元素的所有数量加起来,它具有多种单位类型。如果未列出单位,则根本不包括该单位(例如,没有0值)。然后以替代的基于密钥的格式返回总计数组。

我会亲自尝试,但我想我会搞得一团糟。有人能建议一种优雅的方法来计算我的元素数组以获得理想的结果吗?

阵列:

//Raw Data to be caculated

Array ( 
    [0] => Array ( [hazard] => irritant [quantity] => 1 [unit] => F)
    [1] => Array ( [hazard] => corrosive [quantity] => 2 [unit] => F ) 
    [2] => Array ( [hazard] => health [quantity] => 1 [unit] => F ) 
    [3] => Array ( [hazard] => toxic [quantity] => 1 [unit] => F ) 
    [4] => Array ( [hazard] => environmental [quantity] => 4 [unit] => l )       
    [5] => Array ( [hazard] => health [quantity] => 1 [unit] => l ) 
    [6] => Array ( [hazard] => toxic [quantity] => 2 [unit] => l ) 
    [7] => Array ( [hazard] => irritant [quantity] => 4 [unit] => g ) 
    [8] => Array ( [hazard] => corrosive [quantity] => 2 [unit] => g ) 
    [9] => Array ( [hazard] => toxic [quantity] => 3 [unit] => g ) 
    [10] => Array ( [hazard] => irritant [quantity] => 3 [unit] => K ) 
    [11] => Array ( [hazard] => toxic [quantity] => 2 [unit] => K ) 
    [12] => Array ( [hazard] => environmental [quantity] => 1 [unit] => V ) 
    [13] => Array ( [hazard] => health [quantity] => 2 [unit] => V ) 
    [14] => Array ( [hazard] => irritant [quantity] => 2 [unit] => l ) 
    [15] => Array ( [hazard] => toxic [quantity] => 3 [unit] => l ) 
    [16] => Array ( [hazard] => corrosive [quantity] => 3 [unit] => g ) 
    [17] => Array ( [hazard] => environmental [quantity] => 4 [unit] => g )) 

    etc

期望的结果:

//Array of totaled unit types

Array ( 
   [irritant] => Array( [g] => 4 [l] => 12, [K] => 5, [F] => 2),  
   [corrosive] => Array( [g] => 3 [l] => 7, [K] => 5),
   [hazard] => Array( [g] => 12 [l] => 18, [V] => 2)) 

   etc

1 个答案:

答案 0 :(得分:1)

在插入/更新目标数组的结果之前,您需要创建目标数组并循环遍历原始数组,进行测试和计算。像这样:

<?php
$clean = array();
foreach ($raw_array as $r) {
    $type = $r['hazard'];
    $unit = (isset($r['unit'])) ? $r['unit'] : "";
    $qty = $r['quantity'];
    if (!empty($r['unit'])) // or any other filter for the units
    {
        $clean[$type][$unit] = (isset($clean[$type][$unit])) ?
            $clean[$type][$unit] + $qty :
            $qty;
    }
}
?>

现在,您的$clean变量保存了所需结构的信息。