Wagner Posted January 5, 2015 Share Posted January 5, 2015 $a['a'] = array('a' => '5'); $a['b'] = array('c' => '4'); $a['c'] = array('d' => '3'); $a['d'] = array('z' => '2'); $a['e'] = array('f' => '1'); asort($a); print_r($a); arsort($a); print_r($a); I made the array contents simpler, trying do understand. The 'z' instead of 'e' was introduced to create out of order in the analysis. So, why on earth it results as below? The keys sequence of asort most of the time result in D-B-A-C-E, no matter how much you change the letters and numbers, the arsort result in reverse order of the chaos, go figure !!! The PHP version is 5. Array( [d] => Array ( [z] => 2 ) => Array ( [c] => 4 ) [a] => Array ( [a] => 5 ) [c] => Array ( [d] => 3 ) [e] => Array ( [f] => 1 ))Array( [e] => Array ( [f] => 1 ) [c] => Array ( [d] => 3 ) [a] => Array ( [a] => 5 ) => Array ( [c] => 4 ) [d] => Array ( [z] => 2 ) Quote Link to comment https://forums.phpfreaks.com/topic/293690-asort-problem/ Share on other sites More sharing options...
ginerjm Posted January 5, 2015 Share Posted January 5, 2015 As I read the manual for this function I sense that it doesn't work on multi-dimensional arrays. Why you get a consistent order while trying to do so I do not know, but I think you have to use a custom sorting function. See remarks for assort in the manual. Quote Link to comment https://forums.phpfreaks.com/topic/293690-asort-problem/#findComment-1501835 Share on other sites More sharing options...
Barand Posted January 5, 2015 Share Posted January 5, 2015 It would work for indexed arrays (they will sort on the value of the first item) but not for associative arrays like that one. It does work if the associative arrays have consistent key values for comparisonEG $a['a'] = array('a' => '5'); $a['b'] = array('a' => '4'); $a['c'] = array('a' => '3'); $a['d'] = array('a' => '2'); $a['e'] = array('a' => '1'); That lack of consistency of array keys also make the custom sort option problematical too. 1 Quote Link to comment https://forums.phpfreaks.com/topic/293690-asort-problem/#findComment-1501842 Share on other sites More sharing options...
Barand Posted January 5, 2015 Share Posted January 5, 2015 this will do it $a['a'] = array('a' => '5'); $a['b'] = array('b' => '4'); $a['c'] = array('c' => '3'); $a['d'] = array('z' => '2'); $a['e'] = array('f' => '1'); echo '<pre>'; uasort($a, 'mysortASC'); print_r($a); uasort($a, 'mysortDESC'); print_r($a); echo '</pre>'; function mysortASC($a, $b) { $atmp = array_values($a); $btmp = array_values($b); return $atmp[0] - $btmp[0]; } function mysortDESC($a, $b) { $atmp = array_values($a); $btmp = array_values($b); return $btmp[0] - $atmp[0]; } Quote Link to comment https://forums.phpfreaks.com/topic/293690-asort-problem/#findComment-1501856 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.