Jump to content

[SOLVED] sort an array using 2nd dimension keys


Jim from Oakland

Recommended Posts

Phreax

 

I need to sort an array (configured as shown) based on one of the second dimension keys.

 

[1] ['File_Name'] => test.doc;

[1] ['File_Type'] => MS Word;

[1]['Size'] => 50;

       

[2]['File_Name'] => test.pdf;

[2]['File_Type'] => Adobe PDF

[2]['Size'] => 150

 

[3]['File_Name'] => test.xls;

[4]['File_Type'] => MS Excel;

[5]['Size'] => 60;

 

For example, I'd like the order of the 1st dimension keys (integer indices) to reflect the order if the array is sorted by the "File_Type" key.

 

Jim (sort of)

Link to comment
Share on other sites

For example, to sort by file type:

 

<?php
$array[1]['File_Name'] = 'test.doc';
$array[1]['File_Type'] = 'MS Word';
$array[1]['Size'] = 50;
        
$array[2]['File_Name'] = 'test.pdf';
$array[2]['File_Type'] = 'Adobe PDF';
$array[2]['Size'] = 150;

$array[3]['File_Name'] = 'test.xls';
$array[3]['File_Type'] = 'MS Excel';
$array[3]['Size'] = 60;
function mysort($a,$b){
if($a['File_Type'] == $b['File_Type']){
	return 0;
}
return ($a['File_Type'] < $b['File_Type']) ? -1 : 1;
}
usort($array,'mysort');
echo '<pre>';
print_r($array);
echo '</pre>';
?>

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.