Search code examples
phparrayssortingfile-typealphabetical

How to sort this array by type (dir first and then files)


I wanna know how to sort arrays like this:

$array[] = Array (
    'name' => '/home/gtsvetan/public_html/presta/cms.php'
    'type' => 'text/x-php'
    'size' => 1128
    'lastmod'  => 1339984800
);
$array[] = Array (
    'name' => '/home/gtsvetan/public_html/presta/docs/'
    'type' => 'dir'
    'size' => 0
    'lastmod' => 1329253246
);

I wanna to sort it first by type (folders first and then files) and then alphabetical. But I don't know how to sort it.

Best regards, George!


Solution

  • you can use usort()

    In compare function you do two comparisions on name & type - something like below:

    function compare_f($a,$b) {
    
     if($a['type']=='dir'&&$b['type']!='dir') return 1;
     if($a['type']!='dir'&&$b['type']=='dir') return -1;
     if(substr($a['name'],-1,1)=='/') $a['name']=substr($a['name'],0,-1);
     if(substr($b['name'],-1,1)=='/') $b['name']=substr($b['name'],0,-1);
     $af_array=explode('/',$a['name']);
     $a_name=$af_array[count($af_array)-1];
     $bf_array=explode('/',$b['name']);
     $b_name=$bf_array[count($bf_array)-1];
    
     if($a_name>$b_name) 
        return 1;
      return -1;
    
    }
    
    usort($array,'compare_f');