开发者

sort array by element[1] & element[2]

I have data like below (final sort) and I need to sort the lines based

  1. on the first element asc and
  2. then by the second element desc and
  3. 开发者_Go百科
  4. then by the third element desc

as elements are separated by .

edumate_3rdparty.20110209.1000.hourly.sql
edumate_3rdparty.20110209.0800.hourly.sql
edumate_3rdparty.20101209.Thursday.daily.sql
moodle_acots.20110130.1600.hourly.sql
moodle_acots.20110105.0800.hourly.sql
moodle_tara.20110316.1200.hourly.sql
moodle_tags.20110222.1000.hourly.sql
moodle_tags.20110208.1801.hourly.sql
moodle_will.20110302.1100.hourly.sql
moodle_wollo.20101031.October.4.weekly.sql

how can I do that in php?


Here's an example on how you could sort that data-set.

<?php
$a=array();
$a[]=explode('.','edumate_3rdparty.20110209.1000.hourly.sql');
$a[]=explode('.','edumate_3rdparty.20110209.0800.hourly.sql');
$a[]=explode('.','edumate_3rdparty.20101209.Thursday.daily.sql');
$a[]=explode('.','moodle_acots.20110130.1600.hourly.sql');
$a[]=explode('.','moodle_acots.20110105.0800.hourly.sql');
$a[]=explode('.','moodle_tara.20110316.1200.hourly.sql');
$a[]=explode('.','moodle_tags.20110222.1000.hourly.sql');
$a[]=explode('.','moodle_tags.20110208.1801.hourly.sql');
$a[]=explode('.','moodle_will.20110302.1100.hourly.sql');
$a[]=explode('.','moodle_wollo.20101031.October.4.weekly.sql');
shuffle($a);
// all you need is this function
function special($a, $b){
    if($a[0]!=$b[0])return strcmp($a[0],$b[0]);// asc
    if($a[1]!=$b[1])return strcmp($b[1],$a[1]);// desc
    return strcmp($b[2],$a[2]);// desc
}
usort($a,'special');
// and maybe the above call
echo'<pre>';
foreach($a as $id=>$value)
    $a[$id]=implode('.',$a[$id]);
var_dump($a);
?>

I used Paul's explode idea to get the test scenario going. So thumb's up to him :)


First I would make the data into an array using explode. Then i would sort it using usort.

usort enables you to provide the comparison function for the sort.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜