如何在php中使用字符串作为数学计算公式? [英] how to use a string as formula for mathematical calculations in php?

查看:28
本文介绍了如何在php中使用字符串作为数学计算公式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

mysql 行中存储了几个数学公式供个人使用.即一个字段包含此公式作为字符串 (varchar):(($a+$b)/$c)

There are several mathematical formulas stored in mysql rows for individual usage. i.e. a field contains this formula as a string (varchar): (($a+$b)/$c)

现在在 php 中变量由 foreach 循环动态填充:

Now in php variables are filled dynamically by an foreach loop:

$temp_array[$deviceData["devicename"]] = $deviceSum;

$deviceData["devicename"] 代表 $a、$b、$c.

该数组可以看起来像 $a=>20、$b=>30、$c=>580.

The array can look like $a=>20, $b=>30, $c=>580.

如何在字符串公式中使用这个变量?

感谢您的帮助.

推荐答案

很遗憾,您需要对其进行评估.

Unfortunately, you need to eval it.

如果值是这样的:

$deviceData["devicename"] = [
    'a' => 20,
    'b' => 30,
    'c' => 580
];

您可能想要隔离它们,因为如果有超过 3 个等,您需要 extract() 来使用它们,封装在函数/闭包中会起作用.

You might want to isolate them as you will need to extract() them out to make use if there is more then 3 etc, encapsulating in function/closure would work.

<?php
$formula = '(($a+$b)/$c)';

$deviceData["devicename"] = ['a' => 20, 'b' => 30, 'c' => 580];

$runFormula = function ($formula, $data) { 
    extract($data); 
    return eval('return '.$formula.';'); 
};

echo $runFormula($formula, $deviceData["devicename"]);

https://3v4l.org/I2rbk

或者只是:

extract($deviceData["devicename"]); 
echo eval('return '.$formula.';'); 

但是您正在使用提取的内容污染全局变量表,可能会导致更多问题.

But you're polluting your global variable table with whats extracted, potentially causing more issues.

虽然如果公式是由用户定义的,请不要使用 eval,否则您会遇到安全问题.

Though dont use eval if the formula is defined by the user, or your will have security issues.

在任何情况下,我均不对任何损害承担任何责任,包括,但限于直接、间接、特殊或后果性损害因使用本产品而产生、由此产生或以任何方式与之相关提供的代码,无论是否基于保证、合同、侵权行为或除此以外;伤害是否是由人员或财产造成的或以其他方式;以及损失是否来自或产生的,结果,使用如果此代码.;p

In no respect shall I incur any liability for any damages, including, but limited to, direct, indirect, special, or consequential damages arising out of, resulting from, or any way connected to the use of the code provided, whether or not based upon warranty, contract, tort, or otherwise; whether or not injury was sustained by persons or property or otherwise; and whether or not loss was sustained from, or arose out of, the results of, the use if this code. ;p

这篇关于如何在php中使用字符串作为数学计算公式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆