user546774
user546774

Reputation:

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!

Upvotes: 2

Views: 628

Answers (2)

SHH
SHH

Reputation: 492

You can do something like this..

$dir = array();
$file = array();

$dir = array();
$file = array();

foreach($array as $b=>$v) {
if($v['type'] == "dir") {
    $dir[] = $v;
} else {
    $file[] = $v;
}
}

$combined = array_merge($dir, $file);

Feel free to adjust it.

Upvotes: 0

Jerzy Zawadzki
Jerzy Zawadzki

Reputation: 1985

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');

Upvotes: 1

Related Questions