2011-06-22 32 views
1

我試圖爲列出菜單項的查詢動態分配排序順序(存儲在下面的$ current_sort中)。如何在查詢數組中動態插入orderby語句

如果我硬編碼的排序順序,它工作正常,但是,當我嘗試動態地將排序參數分配給字符串,它失敗。我錯過了什麼?

$current_sort = ", 'orderby' => 'title', 'order' => 'asc'"; 
$myposts = get_posts(
    array(
     'cat' => "$cat,-$catHidden", 
     'numberposts' => $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')); 
+0

是什麼失敗? –

+0

一個方法是動態的而另一個不是?沒有什麼能夠阻止你寫'orderby'=> $ sortField'。將字段名稱和排序方向與'$ currentSort'內的內容區分開來應該不會那麼困難。 – Jon

回答

1

您無法將字符串轉換爲PHP源代碼。 (至少你不應該

試試這個:

$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 
    )   ); 
0

你做錯了,你不必concate..try這樣的:

$ current_sort = 「標題」; $ order =「asc」; $ myposts = get_posts( 陣列( '貓'=> 「$貓, - $ catHidden」, 'numberposts'=> $ my_current_count, '的OrderBy'=> $ current_sort, '訂單'=> $順序 ));

0

就行

'numberposts' => $my_current_count . $current_sort 

字符串連接不等同於創建多個陣列元件,如

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

在第一實例中,numberposts變成含有約排序信息的字符串。 在第二種情況下,numberposts只包含當前計數。

一個更好的選擇可能是:

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