2017-07-26 64 views
2

我想對變量中保存的數據進行排序。我首先將它轉換爲一個數組,然後嘗試按升序對其進行排序,但似乎沒有工作。爲什麼我的php腳本不能排序數組?

這裏是我的代碼

$str = '"10:A", "11:Q", "12:V", "13:A", "14:G", "15:I", "16:E", "17:D", "18:N", "19:R", "1:A", "20:U", "2:X", "3:C", "4:D", "5:R", "6:U", "7:V", "8:I", "9:S"'; 
$cars = (explode(",",$str)); 
$cars = array($cars); 

sort($cars, 1); 
$clength=count($cars); 
for($x=0;$x<$clength;$x++) 
    { 
    echo $cars[$x]; 
    echo "<br>"; 
    } 

什麼解決辦法呢?

+0

哪裏是要排序的代碼?只能看到它打印分割的結果.. –

+0

$ str ='「10:A」,「11:Q」,「12:V」,「13:A」,「14:G」,「15:I」 ,16:E,17:D,18:N,19:R,1:A,20:U,2:X,3:C, 4:D,5:R,6:U,7:V,8:I,9:S, $ cars =(explode(「,」,$ str)); asort($ cars,1); $ clength = count($ cars); ($ x = 0; $ x <$ clength; $ x ++) { echo $ cars [$ x]; echo「
」; } –

回答

0

嘗試rsort

$str = '"10:A", "11:Q", "12:V"'; 
    $cars = (explode(",",$str)); 

    rsort($cars); 
    $clength=count($cars); 
    for($x=0;$x<$clength;$x++) 
     { 
     echo $cars[$x]; 
     echo "<br>"; 
     } 
0

如果你想根據數量進行排序試試這個:

<?php 
function my_sort($a,$b) 
{ 
    $intval_a = filter_var($a, FILTER_SANITIZE_NUMBER_INT); 
    $intval_b = filter_var($b, FILTER_SANITIZE_NUMBER_INT); 
    if(intval($intval_a) > intval($intval_b)) 
    return 1; 
} 
$str = '"10:A", "11:Q", "12:V", "13:A", "14:G", "15:I", "16:E", "17:D", "18:N", "19:R", "1:A", "20:U", "2:X", "3:C", "4:D", "5:R", "6:U", "7:V", "8:I", "9:S"'; 
$cars = explode(',',$str); 
$cars = ($cars); 

usort($cars, "my_sort"); 
$clength=count($cars); 
for($x=0;$x<$clength;$x++) 
{ 
    echo $cars[$x]; 
    echo "<br>"; 
} 
0

有一對夫婦的事情,我已經注意到了。首先,你已經爆炸了產生一個數組的字符串。然後,您將該數組放入另一個數組並嘗試對其進行排序。您應該刪除行$cars = array($cars);

我也建議嘗試對它們進行排序之前,去除串引號和空格,所以你在做排序上10:A而不是"10:A",例如。

另一件事是排序函數應該把一個標誌作爲第二個參數來定義要執行的排序類型。請參閱docs瞭解可用的不同標誌。我猜你希望它進行排序

1:ç...

代替

1:A,2:X,3 A,10: A,11:Q ...

在這種情況下,您應該使用SORT_NATURAL標誌。 (或者,您可以使用natsortfunction)。

這些變化將使以下代碼:

$str = '"10:A", "11:Q", "12:V", "13:A", "14:G", "15:I", "16:E", "17:D", "18:N", "19:R", "1:A", "20:U", "2:X", "3:C", "4:D", "5:R", "6:U", "7:V", "8:I", "9:S"'; 
$str = str_replace(array('"', ' '), '', $str); 
$cars = explode(",",$str); 

sort($cars, SORT_NATURAL); 
$clength = count($cars); 
for($x = 0; $x < $clength; $x++) { 
    echo $cars[$x]; 
    echo "<br>"; 
} 
0

使用natsort()函數

$str = '"10:A", "11:Q", "12:V", "13:A", "14:G", "15:I", "16:E", "17:D", "18:N", "19:R", "1:A", "20:U", "2:X", "3:C", "4:D", "5:R", "6:U", "7:V", "8:I", "9:S"'; 
$cars = (explode(",",$str)); 

natsort($cars); 
echo "<pre>"; print_r($cars); 
foreach($cars as $car) 
{ 
    echo $car."<br>"; 
} 

Check here

希望這會有所幫助。

相關問題