开发者

How to dynamically insert an orderby statement in a query array

I'm trying to dynamically assign the sort order (stored in $current_sort below) for a query that lists menu items.

If I hard code the sort order it works fine, however, when I try to dynamically assign the sort parameters to a string, it fails. What am I missing?

$current_sort = ", 'orderby' => 'title', 'order' => 'asc'";
$myposts = get_posts(
    array(
        'cat' => "$cat,-$catHidden",
        'numberposts' =&开发者_高级运维gt; $my_current_count . $current_sort
        ));

//If I hard code the value of $current_sort it works fine
$myposts = get_posts(
    array(
        'cat' => "$cat,-$catHidden",
        'numberposts' => $my_current_count,
        'orderby' => 'title',
        'order' => 'asc'));


You cannot turn a string into PHP source code. (At least you shouldn't.)

Try this:

$current_sort_order = "title";
$current_sort_direction = "asc";

$myposts = get_posts(array(
      'cat' => "$cat,-$catHidden",
      'numberposts' => $my_current_count,
      'orderby' => $current_sort_order,
      'order' => $current_sort_direction
      )             );


you are doing it wrong, you don't have to concate..try this:

$current_sort = "title"; $order = "asc"; $myposts = get_posts( array( 'cat' => "$cat,-$catHidden", 'numberposts' => $my_current_count, 'orderby'=> $current_sort, 'order' => $order ));


The string concatenation on the line

'numberposts' => $my_current_count . $current_sort

is not equivalent to creating multiple array elements as in

'numberposts' => $my_current_count,
'orderby' => 'title',
'order' => 'asc'));

In the first instance, numberposts becomes a string containing information about the sort. In the second instance, numberposts only contains the current count.

A better option may be:

$orderoption="<TITLE HERE>";
$order_dir="<SORT OPTION HERE>";
$myposts = get_posts(
array(
    'cat' => "$cat,-$catHidden",
    'numberposts' => $my_current_count,
    'orderby' => $orderoption,
    'order' => $order_dir));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜