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)

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

In instances where you want to sort on a string value, the "mysort()" function can simply be

 

function mysort($a,$b)
{
    return strcmp($a['File_Type;], $b['File_Type']);
}

 

(or -strcmp() for DESC sort)

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.