0
這是我的PHP數組: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次。
所以我需要遍歷我的數組,組類型並計算heigth *長度。
我想我的問題是,「類型」可以是任何東西。我無法對它們進行硬編碼。
讓我們開始:
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;
}
非常好。奇蹟般有效。我會閱讀「打印」和「sprintf」,因爲我通常使用「回聲」。現在我不知道如何獲得更多的小數?!謝謝! –
你可以使用'print'或'echo',恕我直言,它並不重要。 [sprintf](http://us2.php.net/sprintf)在你希望輸出格式化字符串的情況下非常有用,但如果你需要使用許多變量,我不會推薦它。你能解釋一下你的意思嗎?「如何獲得更多的小數」? – SaschaM78
好的。謝謝。那麼如果我使用你的「打印」代碼。我根本沒有得到任何小數。只有完整的數字,如:1.但是,如果我回聲我可以有1.345我喜歡回聲,所以我使用它; D –