我在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 :(得分: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";
}
<强>输出强>
Ann 19 897505034 red online
John 22 blue offline
Mike 31 897505034 yellow online
答案 1 :(得分:0)
PHP&gt; = 5.5.0
$pieces = array_multisort(array_column($pieces, 1), SORT_ASC, $pieces);