xProteuSx Posted December 17, 2011 Share Posted December 17, 2011 I've got a few arrays as follows: $array1 = ('A', 54, 'a', 2); $array2 = (, 67, 'b',); $array3 = ('R', 54,,); $array4 = (, 36, 'b'); $array5 = (, 36, 'a',); $array6 = ('FX', 119, 's', 4); $array7 = ('R', 3, 'c',); $superarray = array($array1, $array2, $array3, $array4, $array5, $array6, $array7); Now, I've got a piece of code that sorts $superarray by index[1] of the sub-arrays. The code looks like this: function sortmulti ($array, $index, $order, $natsort=FALSE, $case_sensitive=FALSE) { if(is_array($array) && count($array)>0) { foreach(array_keys($array) as $key) $temp[$key]=$array[$key][$index]; if(!$natsort) { if ($order=='asc') asort($temp); else arsort($temp); } else { if ($case_sensitive===true) natsort($temp); else natcasesort($temp); if($order!='asc') $temp=array_reverse($temp,TRUE); } foreach(array_keys($temp) as $key) if (is_numeric($key)) $sorted[]=$array[$key]; else $sorted[$key]=$array[$key]; return $sorted; } return $sorted; } $sortedarray = sortmulti($superarray, 1, ASC, $natsort=FALSE, $case_sensitive=FALSE) The output is this: R3c 36b 36a A54a2 R54 67b FX119s4 This is great because it goes 3 -> 36 -> 36 -> 54 -> 54 -> 67 -> 119. However, the problem, if you look, is this part: 36b 36a Its sorted everything according to index[1] of the sub-arrays, but now I would like to sort by index[2], then index[3] as well. I'd like the output to look like this: R3c 36a 36b A54a2 R54 67b FX119s4 Any ideas? Because this is way over my head ... Quote Link to comment https://forums.phpfreaks.com/topic/253359-sorting-multidimentional-array-by-two-indexes/ Share on other sites More sharing options...
PFMaBiSmAd Posted December 17, 2011 Share Posted December 17, 2011 In general, you would use array_multisort - <?php // Obtain lists of column values to sort by foreach ($superarray as $key => $row) { $index1[$key] = $row[1]; $index2[$key] = $row[2]; $index3[$key] = $row[3]; } // Sort the data with index1 asc, index2 asc, index3 asc array_multisort($index1, SORT_ASC, $index2, SORT_ASC, $index3, SORT_ASC, $superarray); Quote Link to comment https://forums.phpfreaks.com/topic/253359-sorting-multidimentional-array-by-two-indexes/#findComment-1298763 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.