2014-04-09 33 views
1

我需要一些幫助在PHP中進行表格排序。這條命令:將排序添加到php中的數組中

print_r($pieces); 

打印我:

Array (
[0] => John 
[1] => 22 
[2] => blue 
[3] => offline 
) 

Array (
[0] => Ann 
[1] => 19 
[2] => 897505034 
[3] => red 
[4] => online 
) 

Array (
[0] => Mike 
[1] => 31 
[2] => 897505034 
[3] => yellow 
[4] => online 
) 

然後我填的表格與此記錄。

echo "<tr>"; 
echo "<td>" . $pieces[0] . "</td>"; 
echo "<td>" . $pieces[1] . "</td>"; 
echo "<td>" . $pieces[2] . "</td>"; 
echo "<td>" . $pieces[3] . "</td>"; 
echo "<td>" . $pieces[4] . "</td>"; 
echo "</tr>"; 

John,22,blue,offline 
Ann,19,897505034,red,online 
Mike,31,897505034,yellow,online 

我不知道如何更改年齡,例如排序項填寫該表的順序:

Ann,19,897505034,red,online 
John,22,blue,offline 
Mike,31,897505034,yellow,online 

回答

0

利用Usort

做這樣

<?php 
$pieces=array(array (
    0 => 'John', 
    1 => 22, 
    2 => 'blue', 
    3 => 'offline' 
), 

    array (
     0 => 'Ann', 
     1 => 19, 
     2 => 897505034, 
     3 => 'red', 
     4 => 'online' 
    ), 

    array (
     0 => 'Mike', 
     1 => 31, 
     2 => 897505034, 
     3 => 'yellow', 
     4 => 'online' 
    )); 

usort($pieces,function($a,$b){ return $a[1]<$b[1]?-1:$a[1]!=$b[1];}); 


foreach($pieces as $arr){ 
foreach($arr as $v){ 
    echo $v." "; 
} 
echo "\n"; 

} 

DEMO

輸出

Ann 19 897505034 red online 
John 22 blue offline 
Mike 31 897505034 yellow online 
+0

謝謝!似乎是我想要的,但我明天會在代碼中檢查它。你能否在_return_之後解釋我這部分,特別是_-1_? – Driver

0

PHP> = 5.5.0

$pieces = array_multisort(array_column($pieces, 1), SORT_ASC, $pieces); 
+0

可憐的是我有PHP 5.3.0,現在無法更新... – Driver