2014-10-08 39 views
0

根据用户输入,我执行查询,然后对结果进行一些数学运算。我的问题是,我将数学存储在一个变量中,无法将其作为数学读取。例如:php - 使用变量作为公式

$Math=($ArryDBs[$i]['GSE45728_01']+$ArryDBs[$i]['GSE45728_02'])//this is constructed upon user input 

echo "<table>";//this is coded after Select, where $ArryDBs is generated 
    for ($i=0; $i<$num_rows; $i++){ 
    echo "<tr>"; 
     echo "<td> 1) From Math: ".$Math."</td>"; 
     echo "<td> 2) Direct: ".($ArryDBs[$i]['GSE45728_01']+$ArryDBs[$i]['GSE45728_02'])."</td>"; 
    echo "</tr>"; 
    } 
echo "</table>"; 

输出如下(注意,表达式1)和2)是相同的):

1) From Math: ($ArryDBs[$i]['GSE45728_01']+$ArryDBs[$i]['GSE45728_02']) 2) Direct: 8.23018 
1) From Math: ($ArryDBs[$i]['GSE45728_01']+$ArryDBs[$i]['GSE45728_02']) 2) Direct: 12.46399 
1) From Math: ($ArryDBs[$i]['GSE45728_01']+$ArryDBs[$i]['GSE45728_02']) 2) Direct: 15.08906 

值2)直接就是我想要的。但它根据用户输入而改变。这就是为什么我将表达式存储在变量中。它从字面上读取字符串。所有相关的问题都表明使用eval(),尽管总是人(和手册本身)不鼓励它的使用。

我的问题:我如何获得$ Math读取作为执行操作?

+0

如果我用浮点数代替上面的变量,我会得到预期的输出:1)从数学:67 2)直接:67'。你有没有尝试将你的变量转换为正确的数值? – Crackertastic 2014-10-08 17:57:20

+0

@Crackertastic:我不确定如果是正确的数值,并且会检查我的代码。为了简单起见,我直接写了$ Math,但它实际上是用'$ ForMath [$ key]。=“\ $ ArrayDBs [\ $ i] ['”。$ key。“_”。$ matches [1] [$ n]。“']”; $ Math = array_values($ ForMath);'并且我的问题的代码被称为$ Math [0]或类似的。无论如何,当回应“阅读”是与我想评估的表达相同。我会仔细审查我的代码(我绝不是专家......)。谢谢。 – CMArg 2014-10-08 18:28:35

+0

通常,PHP对于在算术之前认为字符串“认为”是数字并为您进行投射很好,但PHP并不完美。你总是可以尝试在变量前面放置'(float)'或'(int)'来告诉PHP来投射一个变量。 PHP的[settype()](http://php.net/manual/en/function.settype.php)函数也很有帮助,因为它会返回一个布尔值,让您知道投射是否成功。 – Crackertastic 2014-10-08 18:36:31

回答

0

PHP不能递归执行。您不能将PHP代码嵌入到字符串中,并希望PHP也能执行它。

例如

<?php 

echo "Hello <?php echo 'world' ?>"; 

?> 

是要打印出来,从字面上:

Hello <?php echo 'world' ?> 

如果你想有一个变量的内容被视为“数学”(如PHP代码),那么你就必须执行这些内容,例如

php > $foo = "echo 1+1;"; 
php > eval($foo); 
2 

并注意变量的内容必须是有效的php代码。 eval('1+1')将计算出2,但由于该值没有分配到任何位置或返回任何内容,因此将被简单地丢弃。


评论随访:

php > $a = 1; 
php > $b = 2; 
php > $c = 3; 
php > $d = 4; 
php > $foo = '$bar = ($a + $b) * ($c + $d);'; 
php > eval($foo); 
php > echo $bar; 
21 

作品如预期。

+0

你说得对。那就是问题所在。但是我仍然无法“完全”评估$ Math [0],它的内容如下:($ ArrayDBs [$ i] ['GSE45728_01'] + $ ArrayDBs [$ i] ['GSE45728_02'])。当我用'eval(“\ $ Math2 = \”$ Math [0] \“;”);'尝试时,响应是'(Array ['GSE45728_01'] + Array ['GSE45728_02'])'正在评估'$ ArrayDBs [$ i]',但不是数组的第二个组件('['GSE45728_02']')。任何想法? – CMArg 2014-10-08 19:58:56

+0

双引号字符串中多维数组的标准php行为。 (卷曲)语法“:http:// php。net/manual/zh/language.types.string.php – 2014-10-08 20:02:07

+0

几乎在那里。我需要更多的学习和理解,并且会自己尝试,但如果有人能够帮助我更多,我会很感激。如果变量被定义为'({$ ArregloDBs [$ i] ['GSE45728_01']} + {$ ArregloDBs [$ i] ['GSE45728_02']})/({$ ArregloDBs [$ i] ['GSE45728_03'] } + {$ ArregloDBs [$ i] ['GSE45728_04']})',我得到'(5.38084 + 2.84934)/(3.28155 + 3.96505)'。 Id est,它正确评估数组值,但不执行数组值之间的操作。我还需要什么?也许eval()的eval()? – CMArg 2014-10-08 21:10:59