【问题标题】:PHP, Calculation Key in arrayPHP,数组中的计算键
【发布时间】:2015-07-07 06:40:05
【问题描述】:

我有一个这样的数组

Array
(
   [0] => LK10110000
   [1] => +
   [2] => LK10120000
   [3] => -
   [4] => LK10130000
)

我想从该数组中根据以下数组计算序列进行查询

预期结果:

 Value = ResultMysql [LK10110000] + ResultMysql [LK10120000] - ResultMysql [LK10130000]`

【问题讨论】:

  • 你试过了吗
  • 我仍然对逻辑感到困惑
  • 我认为它会是 $ResultMysql[0].$ResultMysql[1].$ResultMysql[2].$ResultMysql[3].$ResultMysql[4]
  • @sikancil。不清楚。尝试更好地解释它。
  • 我有一个变量 LK10110000; +; LK10120000; -; LK10130000 有三个变量键和两个数学符号,然后我爆炸“;”获取一个新变量,该变量在mysql查询中作为key 简单解释:Result = 查询结果数组[0] + (数组[1]) 查询结果数组[2] - (数组[3]) 的查询结果数组 [4]

标签: php mysql arrays


【解决方案1】:

根据您的问题和 cmets,我了解到您有一个包含表达式的字符串,您需要运行一些查询并根据表达式计算结果。而且问题是你事先不知道表达式。

我假设你的表达式只包含加法和减法。

如果它还包含乘法或除法、括号、函数或其他运算符,则其余答案不适用,它需要更复杂的代码来处理运算符优先级、括号和函数调用。

想法

  1. 0初始化保存最终结果的变量。
  2. 像你已经做的那样将字符串分成几部分。
  3. + 符号添加到片段数组中。
  4. 从数组中取出前两块。第一个是符号,第二个是变量。
  5. 使用变量作为参数来编写和运行查询。
  6. 将查询返回的值与最终结果相加或相减(检查在第 4 步中检索到的符号以了解它是 add 还是 subtract)。
  7. 如果数组中仍有未处理的片段,请从步骤 4 开始重复。

代码

代码比上面描述的越来越清晰了:

// This is the input expression
$expression = 'LK10110000; +; LK10120000; -; LK10130000';
// Step 1
$total = 0;
// Step 2
$pieces = explode(';', $pieces);
if (count($pieces) % 2 != 1) {
    // The expression is incorrect; handle the situation somehow
    //
    // A valid expression must contain an odd number of items
    // (alternating value and operator, starting and ending with a value)
}
// Extra processing: remove the padding spaces from around the values
// to ensure testing the sign against '-' works correctly
$pieces = array_map('trim', $pieces);
// Step 3
array_unshift($pieces, '+');
// Step 4
do {
    $sign  = array_unshift($pieces);
    $value = array_unshift($pieces);
    // Step 5
    // ... use $value here to generate and run the query
    // ... put the value returned by the query in variable $result
    $result = 1;       // <-- replace this line
    // Step 6
    if ($sign === '+') {
        $total += $result;
    } elseif ($sign === '-') {
        $total -= $result;
    } else {
        // This is an error in the expression; handle it somehow
    }
// Step 7
} while (count($pieces));
// The output is in $total
echo($total);

备注

如果查询返回的不是单个数值而是一组记录($value 是一个标量、数组或对象的数组),则调整步骤 6 中的代码并使用适当的 $value 合并到 @ 987654328@。同时使用正确的标量/数组/对象数组初始化$total

“适当的合并”的确切定义取决于您的应用程序的规则。要实现它,您可能必须遍历 $value 的元素,并且对于每个元素,在 $total 中找到相应的元素并更新它,如果不存在则插入它。

【讨论】:

    猜你喜欢
    • 2021-03-23
    • 2020-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多