MetroidMaster1914 Posted February 10, 2010 Share Posted February 10, 2010 I have an array that I've compiled, which, when printed, reads as: Array ( [1] => Array ( [file] => wallpaper1024.jpg [width] => 1024 [height] => 768 ) [2] => Array ( [file] => wallpaper800.jpg [width] => 800 [height] => 600 ) ) What I'm trying to do is sort it by the width from least to greatest, so that it results in: Array ( [1] => Array ( [file] => wallpaper800.jpg [width] => 800 [height] => 600 ) [2] => Array ( [file] => wallpaper1024.jpg [width] => 1024 [height] => 768 ) ) I know that there are a number of array sorting functions available, but I can't seem to figure out how to use them to sort this array like I need it to be. Can anyone help me out? Link to comment https://forums.phpfreaks.com/topic/191583-help-needed-sorting-a-2d-array/ Share on other sites More sharing options...
PravinS Posted February 10, 2010 Share Posted February 10, 2010 Try this function function sort_array($array, $key, $order) { if ($order=="DESC") $or="arsort"; else $or="asort"; for ($i = 0; $i < sizeof($array); $i++) { $sort_values[$i] = $array[$i][$key]; } $or($sort_values); reset ($sort_values); while (list ($arr_key, $arr_val) = each ($sort_values)) { $sorted_arr[] = $array[$arr_key]; } return $sorted_arr; } Link to comment https://forums.phpfreaks.com/topic/191583-help-needed-sorting-a-2d-array/#findComment-1009925 Share on other sites More sharing options...
MetroidMaster1914 Posted February 10, 2010 Author Share Posted February 10, 2010 Had modify my surrounding code a bit, but it worked like a charm! Thank you so much. Link to comment https://forums.phpfreaks.com/topic/191583-help-needed-sorting-a-2d-array/#findComment-1009933 Share on other sites More sharing options...
teamatomic Posted February 10, 2010 Share Posted February 10, 2010 foreach ($array as $key => $row) { $width[$key] = $row['width']; } array_multisort($width, SORT_DESC, $array); HTH Teamatomic Link to comment https://forums.phpfreaks.com/topic/191583-help-needed-sorting-a-2d-array/#findComment-1009934 Share on other sites More sharing options...
teamatomic Posted February 10, 2010 Share Posted February 10, 2010 oops change DESC to ASC HTH Teamatomic Link to comment https://forums.phpfreaks.com/topic/191583-help-needed-sorting-a-2d-array/#findComment-1009943 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.