如何用数组值编写php三元运算符 [英] How to write php ternary operator with array value

查看:43
本文介绍了如何用数组值编写php三元运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以将其写为三元运算符?

Is it possible to write this as a ternary operator?

if($catId){
    $clauses[] ='`category` = '.$catId;
}

当我尝试以下操作时,我仍然将一个值添加到数组中

When I try the following I still get a value added to the array

$clauses[] = ($catId)?'`category` = '.$catId:null;

作为参考,我在使用 where 子句构建 sql 查询时使用它

For reference, Im using this in building a sql query with a where clause

$where = null;
$clauses = array();
if($manId){
    $clauses[] ='`man` = '.$manId;
}
if($catId){
    $clauses[] ='`category` = '.$catId;
}
if(count($clauses)){
    $where = implode (' && ',$clauses);
    $where = 'WHERE '.$where;
}

$sql = "SELECT * FROM `products` $where ORDER BY `isfeatured`,`sortvalue`";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result)){
    print $row['name'].'<br>';
}

推荐答案

是的.如果你真的想使用三元,可能是这样的:

Yes. If you really want to use a ternary, it is possible like this:

$catId ? $clauses[] = "`category`=$catId" : null;

这里的赋值发生在三元的真实部分,而不是赋值三元的结果.

Here the assignment happens in the true portion of the ternary instead of assigning the result of the ternary.

不过,使用三元是没有意义的,因为如果变量为空,你不想做任何事情,所以三元的假部分是无关紧要的.应该具有基本相同效果的较短版本是:

Using a ternary is kind of pointless, though, because you don't want to do anything if the variable is empty, so the false portion of the ternary is irrelevent. A shorter version that should have basically the same effect is:

$catId && $clauses[] = "`category`=$catId";

就我个人而言,我认为您已经拥有的方式对于以后必须处理此问题的任何人来说都更具可读性和友好性,因为它不那么古怪和笨拙,但这是可能的.

Personally, I think the way you already have it is more readable and friendlier to anyone who has to work on this later by being less weird and hacky, but it is possible.

这篇关于如何用数组值编写php三元运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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