Jim from Oakland Posted October 28, 2007 Share Posted October 28, 2007 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 https://forums.phpfreaks.com/topic/75139-solved-sort-an-array-using-2nd-dimension-keys/ Share on other sites More sharing options...
GingerRobot Posted October 28, 2007 Share Posted October 28, 2007 You'll need to use the usort() function to define your own sorting criteria. Link to comment https://forums.phpfreaks.com/topic/75139-solved-sort-an-array-using-2nd-dimension-keys/#findComment-380011 Share on other sites More sharing options...
GingerRobot Posted October 28, 2007 Share Posted October 28, 2007 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 https://forums.phpfreaks.com/topic/75139-solved-sort-an-array-using-2nd-dimension-keys/#findComment-380014 Share on other sites More sharing options...
Barand Posted October 28, 2007 Share Posted October 28, 2007 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) Link to comment https://forums.phpfreaks.com/topic/75139-solved-sort-an-array-using-2nd-dimension-keys/#findComment-380075 Share on other sites More sharing options...
GingerRobot Posted October 29, 2007 Share Posted October 29, 2007 You learn something new everyday! Link to comment https://forums.phpfreaks.com/topic/75139-solved-sort-an-array-using-2nd-dimension-keys/#findComment-380168 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.