xProteuSx Posted December 16, 2011 Share Posted December 16, 2011 I've got a multidimensional array that has 2 columns. The first column is numerical (country_id), and the second column is text (country_name), which may or may not be data that will be turned into an array. Looks something like this: column 1 (index 0) = 42 column 2 (index 1) = Great Britain|England I use a while loop to create an array of these rows, then a use a foreach loop to go through index[1] of each row. If there is a single name for a country, it is added to a new array, but if there is more than one name for a country, then both names are added to the new array. So, for example, if we had this data: row1 column 1 (index 0) = 12 column 2 (index 1) = Algeria row2 column 1 (index 0) = 22 column 2 (index 1) = Ethiopia row3 column 1 (index 0) =42 column 2 (index 1) = Great Britain|England Then the final array would look like this: index[0] = 12 index[1] = Algeria index[0] = 22 index[1] = Ethiopia index[0] = 42 index[1] = Great Britain index[0] = 42 index[1] = England Now I would like to sort by index[1] to get the following alphabetical order: index[0] = 12 index[1] = Algeria index[0] = 42 index[1] = England index[0] = 22 index[1] = Ethiopia index[0] = 42 index[1] = Great Britain What do I use? I've fooled around with sort, usort, asort ... can't figure it out. Thanks in advance. Quote Link to comment Share on other sites More sharing options...
SergeiSS Posted December 16, 2011 Share Posted December 16, 2011 Here usort() is a function that you need. The only thing that you need - to create correct call-back function. It might compare second columns from 2 elements and return correct value. Quote Link to comment Share on other sites More sharing options...
xProteuSx Posted December 16, 2011 Author Share Posted December 16, 2011 Got this tidbit from the PHP website: 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; } Quote Link to comment 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.