[英]PHP using concatenation logical operator between two values - maths
Hi I'm retrieving some values form my database using Laravel in order to calculate something.嗨,我正在使用 Laravel 从我的数据库中检索一些值以计算某些内容。
This is a really simple version of what I have (i have a config which has multiple of these values and I pass the model names and values and Im able to do this on the fly):这是我所拥有的一个非常简单的版本(我有一个配置,其中包含多个这些值,我传递了模型名称和值,并且我可以即时执行此操作):
$substitute['operator'] = '/';
$substitute['value'] = '5';
$select = User::->where('id','1')
->pluck('holidaysperyear');
$replace = $select.$substitute['operator'].$substitute['value'];
If I concatenate the logical operator the values are all printed out eg 21/5如果我连接逻辑运算符,则所有值都会打印出来,例如 21/5
however if I do this:但是,如果我这样做:
$replace = $select/$substitute['value'];
The division is done successfully but the problem I have is that I have config which could want the operator to be multiplied or addition so I would need the flexibility to pass in the operator, any ideas why it doesn't work like that?除法成功完成,但我遇到的问题是我的配置可能希望运算符乘以或加法,所以我需要灵活地传递运算符,任何想法为什么它不能那样工作? help is appreciated!
帮助表示赞赏!
In order to do what you're asking, you would have to eval()
the string.为了执行您的要求,您必须
eval()
字符串。 That isn't good practice however, so here is another solution.然而,这不是一个好习惯,所以这是另一种解决方案。
You could use a switch statement with each valid operator, and just perform the proper operation in the case statement.您可以对每个有效运算符使用 switch 语句,并在 case 语句中执行正确的操作。 Like this:
像这样:
switch ($substitute['operator']) {
case '*':
$replace = $select * $substitute['value'];
break;
case '/':
$replace = $select / $substitute['value'];
break;
case '+':
$replace = $select + $substitute['value'];
break;
case '-':
$replace = $select - $substitute['value'];
break;
case '%':
$replace = $select % $substitute['value'];
break;
case '**':
$replace = $select ** $substitute['value']; // or pow() if you use < PHP 5.6
break;
// more cases...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.