这是我的PHP数组:
Array (
[0] => Array ( [heigth] => 6300 [type] => A [length] => 2370 )
[1] => Array ( [heigth] => 1150 [type] => B [length] => 5510 )
[2] => Array ( [heigth] => 1150 [type] => C [length] => 7150 )
[3] => Array ( [heigth] => 1150 [type] => A [length] => 3540 )
);
现在我想计算每种类型的总面积。您可以看到类型"A"存在 2 次。
所以我需要遍历我的数组、组类型并计算高度 * 长度。
我想我的问题是"类型"可以是任何东西。我无法对它们进行硬编码。
所以让我们开始:
for($i = 0; $i < $rowCountArray; $i++){
//Grab type
$type = $array[$i]['type'];
//Calc Area
$area = $array[$i]['heigth'] * $array[$i]['length'];
//Here i need something like an if statement. But also i need dynamic added vars?!
//if(type is NEW) if(type exists)
$type1_Area += $area; //Seperated by types
$type2_Area += $area;
}
如何构建一个总和数组?
$arrSums= array();
for($i = 0; $i < $rowCountArray; $i++){
$type = $array[$i]['type'];
$arrSums[$type] += $array[$i]['heigth'] * $array[$i]['length'];
}
// display the array elements with sums
foreach ($arrSums as $key => $value) {
print sprintf('sum for %s is: %d', $key, $value);
}
print sprintf('total sum is: %d', array_sum($arrSums));
未测试,但这应该有效吗?
如果数组中尚未包含面积,则只需将面积设置为 0,然后就可以根据需要处理每种类型的总面积。
$arr = array(
array('height' => 6300, 'type' => 'A', 'length' => 2370),
array('height' => 1150 , 'type' => 'A', 'length' => 5510 ),
array('height' => 1150 , 'type' => 'A', 'length' => 7150),
array('height' => 1150 , 'type' => 'A', 'length' => 3540 ),
);
$area = array();
foreach ($arr AS $item) {
if (!isset($area[$item['type']])) $area[$item['type']] = 0;
$area[$item['type']] += $item['type'] * $item['length'];
}