我不知道在php中的数组中使用if else语句是不可能的。我搜索了stackoverflow,发现速记版本应该可以正常工作。
我尝试了但仍有错误且页面无法加载,我的代码:
query_posts (array(
($prefooter_order_logic == 'xviews' ? "'v_sortby' => 'views', 'v_orderby' => 'desc'," : "")
'order' => 'DESC',
'orderby' => $prefooter_order_logic,
'posts_per_page' => '10',
'post_type' => 'post',
'category_name' => $prefooter_category_select
));
这不会给我错误:
但它不起作用......
($prefooter_order_logic == 'xviews' ? "
'v_sortby' => 'views',
'v_orderby' => 'desc',
" : "
'order' => 'DESC',
'orderby' => $prefooter_order_logic,
"),
我决定停止玩耍并以最简单的方式行事:
顺便问一下,如果这是最好的方法吗?不是吗? if ($prefooter_order_logic == 'xviews') {
query_posts (array(
'v_sortby' => 'views',
'v_orderby' => 'desc',
'posts_per_page' => '10',
'post_type' => 'post',
'category_name' => $prefooter_category_select
));
} else {
query_posts (array(
'order' => 'DESC',
'orderby' => $prefooter_order_logic,
'posts_per_page' => '10',
'post_type' => 'post',
'category_name' => $prefooter_category_select
));
}
答案 0 :(得分:2)
首先问题是)
之后?
和,
之后没有$prefooter_order_logic == 'xviews' ? "'v_sortby' => 'views', 'v_orderby' => 'desc'," : "")
($prefooter_order_logic == 'xviews' )? "'v_sortby' => 'views', 'v_orderby' => 'desc'," : ""),
应该是
{{1}}
答案 1 :(得分:2)
这会产生syntax error, unexpected T_CONSTANT_ENCAPSED_STRING
,因为你在这一行末尾缺少一个逗号:
($prefooter_order_logic == 'xviews' ? "'v_sortby' => 'views', 'v_orderby' => 'desc'," : ""),
^ here
编辑:
根据您的条件创建数组后,只需修改数组:
$arr = array(
'posts_per_page' => '10',
'post_type' => 'post',
'category_name' => $prefooter_category_select
);
if($prefooter_order_logic == 'xviews')
{
$arr['v_sortby'] = 'views';
$arr['v_orderby'] = 'desc';
}
else
{
$arr['order'] = 'DESC';
$arr['orderby'] = $prefooter_order_logic;
}
query_posts($arr);
或者,使用array_merge()
:
$arr = array(
'posts_per_page' => '10',
'post_type' => 'post',
'category_name' => $prefooter_category_select
);
$arr = $prefooter_order_logic == 'xviews' ? array_merge($arr, array('v_sortby' => 'views', 'v_orderby' => 'desc')) : array_merge($arr, array('order' => 'desc', 'orderby' => $prefooter_order_logic));
query_posts($arr);
答案 2 :(得分:1)
你应该指明你有什么错误,而且很难说你想要做什么。
但是,您在三元运算符的行末缺少逗号:
'desc'," : "")
之后加一个逗号。
答案 3 :(得分:0)
我猜你无法像这样评估PHP代码:
"'v_sortby' => 'views', 'v_orderby' => 'desc',"
它应该看起来像PHP解释器的文本,而不是数组的一部分,但我不确定。