我有一個動態數組。
允許假設對動態數組執行數學計算
array (size=3)
0 => string '20' (length=2)
1 => string '-' (length=1)
2 => string '5' (length=1)
其結果將是未定義20-5 = 5
數組大小,如何動態解決呢?
我有一個動態數組。
允許假設對動態數組執行數學計算
array (size=3)
0 => string '20' (length=2)
1 => string '-' (length=1)
2 => string '5' (length=1)
其結果將是未定義20-5 = 5
數組大小,如何動態解決呢?
您可以使用以下代碼。當然,它有一些限制。取決於你想做什麼以及你爲什麼這樣做。
<?php
$array = array(
'20',
'-',
'5',
'*',
'10'
);
$output = null;
$symbol = null;
foreach ($array as $item) {
if ($item == '+' || $item == '-' || $item == '*' || $item == '/') {
if ($output === null) {
die("First item should be numeric! ");
}
$symbol = $item;
continue;
} elseif (!is_numeric($item)) {
die("unknown symbol: " . $item);
}
// is numeric
// first symbol
if ($output == null) {
$output = $item;
continue;
}
if ($symbol === null) {
die('Two numbers in a row!!');
}
switch ($symbol) {
case '+':
$output += $item;
break;
case '-':
$output -= $item;
break;
case '*':
$output *= $item;
break;
case '/':
$output /= $item;
break;
}
}
echo "Calculation is: " . $output;
小錯誤除法:'$ output&= $ item;'應該是'$ output/= $ item;' – maxhb
phps最討厭和擔心函數的少數情況之一派上用場。
邪惡eval()
:
$input = array('20', '-', '5');
// build formula from array by glueing values together
$formula = implode(' ', $input);
// execute the formula and store result in $result
eval('$result = ' . $formula . ';');
// voila!
echo $formula . ' = ' . $result;
有關使用eval()
的好處是,你可以在PHP中使用已知的,並完全支持甚至搬運支架的所有數學運算。
請訪問http://sandbox.onlinephpfunctions.com/code/71ffc94238a5510cd7b24632fc7a8b9b5cb2c2c0瞭解更多關於測試定義公式的示例。
謝謝@maxhb。你救了我一天 –
如果這真的救了你一天,你應該接受解決方案;-) – maxhb
'20 - 5 = 5'好的。 – Rizier123
它可能有多少個不同的操作數?像((4/2)* 5 - 1]這樣的東西在9號陣列中是可能的嗎? –
opertore將是+, - ,*,/但數組中操作數的數量沒有定義,但我的問題是如何解決這個使用數組? –