Jump to content

Sorting Array


drisate

Recommended Posts

hey guys!

i have an arrays that looks like this:

 

Array
(
[0] => Array
(
[name] => backup_fghj.sql.gz
[size] => 10056579
[perm] => -rw-r--r--
[type] => file
[time] => 22 February 2012 18:53:16
[stamp] => 85745
)

[1] => Array
(
[name] => backup_sdfg.sql.gz
[size] => 13755947
[perm] => -rw-r--r--
[type] => file
[time] => 16 November 2012 14:26:13
[stamp] => 25745
)

[2] => Array
(
[name] => backup_dfgh.sql.gz
[size] => 11936839
[perm] => -rw-r--r--
[type] => file
[time] => 15 September 2012 22:18:55
[stamp] => 84574
)

[3] => Array
(
[name] => backup_erty.sql.gz
[size] => 11009205
[perm] => -rw-r--r--
[type] => file
[time] => 22 July 2012 09:08:16
[stamp] => 34574
)

)

 

 

I need to sort it by stamp desc ... how can i do that?

 

 $file = dir_list("../forum/CPadmin/backups");

 $f=0;
 foreach($file as $fichier){
	 if (strstr($file[$f]['name'], '.gz')){
		 $page_content .= '<a href="/forum/CPadmin/backups/'.$file[$f]['name'].'">'.$file[$f]['time'].'</a></br>';
	 }
 $f++;

Edited by drisate
Link to comment
Share on other sites

function customSort($a, $ B)
{
if($a['stamp'] != $b['stamp'])
{
	return ($a['stamp'] < $b['stamp']) ? -1 : 1;
}
return 0;
}

//use usort() to sort array with custom function
usort($YOURARRAY, 'customSort');

//The original array variable is now sorted

Edited by Psycho
Link to comment
Share on other sites

for a DESC numeric sort the function just need to be

 

function customSort( $a, $b )
{
return $b['stamp'] - $a['stamp'];
}

 

Absolutely. I tend to use the initial check to see if the values are different (as in my example) because it let's me easily add additional sorting criteria.So, if the 'stamp' values were the same there could be some additional logic to then sort on field#2, then field#3, etc.

 

So, using your more elegant solution . . .

function customSort($a, $ B)
{
   if($a['stamp'] != $b['stamp']) { return $b['stamp'] - $a['stamp']; }
   if($a['field2'] != $b['field2']) { return $b['field2'] - $a['field2']; }
   if($a['field3'] != $b['field3']) { return $b['field3'] - $a['field3']; }
   return 0;
}

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.