2016-02-05 69 views
-4

大家好我有陣列系列季和劇集的名字 這裏是我的陣列PHP的排序數組項問題

- The Flash 2.Sezon 11.Bölüm 
- The Flash 2.Sezon 1.Bölüm 
- The Flash 1.Sezon 20.Bölüm 
- The Flash 2.Sezon 3.Bölüm 
- The Flash 3.Sezon 3.Bölüm 

(sezon =>季節,bolum =>情節在我的語言)

我要首發排序他們最後一集

- The Flash 1.Sezon 20.Bölüm 
- The Flash 2.Sezon 1.Bölüm 
- The Flash 2.Sezon 3.Bölüm 
- The Flash 2.Sezon 11.Bölüm 
- The Flash 3.Sezon 3.Bölüm 

我試圖ASORT功能,但沒有奏效。以正確的順序大多數項目,但他們中的一些not.Here是我的全碼:

$args=array('post_type' => 'bolum', 
      'posts_per_page' =>-1, 
      'orderby' => 'title', 
      'meta_query' => array(array(
            'key' => 'bolum_dizi', 
            'value' => '"' . $post_id . '"', // matches exaclty "123", not just 123. This prevents a match for "1234" 
            'compare' => 'LIKE' 
             ) 
           ) 
      ); 
$episodes = get_posts($args); 

這也是我如何訂購和打印

asort($episodes); 
foreach($episodes as $episode){ 
echo $episode->post_title .'\n';} 

我怎樣才能做到這一點? 非常感謝。

+3

你的代碼是什麼?你有什麼嘗試?預期產出是多少?實際產出是多少?我們可以幫助您解決代碼中的問題,但我們無法理解您的想法。哦,也許可以用你的代碼中定義的相同格式給你的輸入數據。 –

+0

我在帖子中提到過。我嘗試了($ episodes); –

+2

只是發佈相關的代碼。而不僅僅是一個功能的名稱,沒有足夠的信息來說明它是如何使用的。 –

回答

2

你要找的是所謂自然排序可以使用natsort()功能來實現:

<?php 

$arr = array(
'- The Flash 2.Sezon 11.Bölüm', 
'- The Flash 2.Sezon 1.Bölüm', 
'- The Flash 1.Sezon 20.Bölüm', 
'- The Flash 2.Sezon 3.Bölüm', 
'- The Flash 3.Sezon 3.Bölüm', 
); 

natsort($arr); 

echo '<pre>'; 
var_dump($arr); 
echo '</pre>'; 

其結果將是:

array(5) { 
    [2]=> 
    string(30) "- The Flash 1.Sezon 20.Bölüm" 
    [1]=> 
    string(29) "- The Flash 2.Sezon 1.Bölüm" 
    [3]=> 
    string(29) "- The Flash 2.Sezon 3.Bölüm" 
    [0]=> 
    string(30) "- The Flash 2.Sezon 11.Bölüm" 
    [4]=> 
    string(29) "- The Flash 3.Sezon 3.Bölüm" 
} 

對於對象,你必須數組使用usortstrnatcmp

usort($episodes, function($a, $b) { 
    return strnatcmp($a->post_title, $b->post_title); 
}); 
+0

它給了500內部服務器錯誤。只是認爲我做的是用natsort替換asort。我再次更換asort並修復了500個問題。爲什麼它不適合我?也許PHP版本? –

+0

你有什麼版本的PHP? –

+0

根據文檔,它應該可用於PHP 4,PHP 5,PHP 7.檢查Apache的error_log看看有什麼不對 –