-2

如果我有如下字符串:

$string = 1x2,3x5,6x6,;

每个部分包含例如:

1 = 数量,x2 = 数量。

有没有办法将逗号之间的每个段分开,然后用数量乘以数量?

谢谢

4

2 回答 2

1

是的 - 通过使用explodeand list(你可以不使用它list,但使用它会更容易):

$string = "1x2,3x5,6x6";
$total = 0;
$explode = explode(",", $string);
foreach ($explode as $explodeSegment) {
    if (trim($explodeSegment) != "") {
        list($amount, $quantity) = explode("x", $explodeSegment);
        $total += ((int)$amount * (int)$quantity);
    }
}
var_dump($total); //int(53)

演示

于 2013-05-28T14:19:22.360 回答
0

您可以使用这样的功能。

function evaluateExpressions($strings){
    $expressions = explode(",", $strings);
    $expressions = array_filter($expressions);
    $matches = array();
    $results = array();
    foreach($expressions as $expression){
          if (preg_match_all("/([0-9]+)([^0-9])([0-9]+)/", $expression, $matches)){
            array_shift($matches);
            print_r($matches);
            $lh = array_shift($matches)[0];
            $op = array_shift($matches)[0];
            $rh = array_shift($matches)[0];

            switch($op){
                case "x":
                    $results[] = $lh * $rh;
                    break;
                case "+":
                    $results[] = $lh + $rh;
                    break;
                case "-":
                    $retults[] = $lh + $rh;
                    break;
                case "/":
                    $results[] = $lh + $rh;
                    break;
                default:
                    throw new Exception("I don't understand how to use ".$op);
            }


          } else {
            throw new Exception("Malformed Expression List");
          }
    }
    return $results;
}

If 将评估 2 个术语数学表达式的列表并返回结果数组

使用示例:

$strings = "1x2,3x5,6x6,";
$dat = evaluateExpressions($strings);
print_r($dat);

会产生

Array
(
    [0] => 2
    [1] => 15
    [2] => 36
)

作为奖励,它还知道如何使用其他简单的数学运算符 (+ - x /)

于 2013-05-28T14:31:41.257 回答