Languages :: PHP :: Sorting multidimensional array |
|||
| By: PHP newbee |
Date: 01/10/2003 00:00:00 |
Points: 125 | Status: Answered Quality : Excellent |
|
Hi! Trying to sort this array by numbers: $d[0][0] = "blablajflfj"; $d[0][1] = 123123; $d[0][2] = "hjkh"; $d[1][0] = "balbal"; $d[1][1] = 123; $d[1][2] = "asgasg"; $d[2][0] = "sffssl"; $d[2][1] = 99999; $d[2][2] = "sdg"; Have tried both the usort() with a textbook function and a selfbuilt function. Both function sorts the arrays by the first integer in the number like this: 1,11,2,222 and not by the value of the number. Any ideas? |
|||
| By: PHP newbee | Date: 01/10/2003 00:13:00 | Type : Comment |
|
| Might it be that the number is a string? |
|||
| By: VGR | Date: 01/10/2003 00:26:00 | Type : Answer |
|
| yes, apparently, it uses the lexical order. Try the usort() with your on function. basically : just typecast the two elements using "(integer)" |
|||
| By: sumotimor | Date: 01/10/2003 02:02:00 | Type : Comment |
|
| For your usort() function, be sure to reference the correct index in the array, instead of the array itself. Otherwise, the first position of the array will be compared. Example: <?php $d[0][0] = "blablajflfj"; $d[0][1] = 123123; $d[0][2] = "hjkh"; $d[1][0] = "balbal"; $d[1][1] = 123; $d[1][2] = "asgasg"; $d[2][0] = "sffssl"; $d[2][1] = 99999; $d[2][2] = "sdg"; usort($d, 'cmp'); function cmp($a, $b) { return $a[1] > $b[1]; } print_r($d); ?> |
|||
| By: sumotimor | Date: 01/10/2003 02:03:00 | Type : Comment |
|
| The above sorts by the [1] index of each item in the $d array, which is the integer element. Note: If this were the 1st element in each subarray, you could just call sort() on your main array, which might be a bit faster than using the callback with usort() |
|||
| By: PHP newbee | Date: 01/10/2003 03:05:00 | Type : Comment |
|
| Eventhough your help did clear up a few things, shmert. The actual problem was solved by VGR. Thanks to both of you! Just whish I could split the points between you! |
|||
| By: sumotimor | Date: 01/10/2003 04:38:00 | Type : Comment |
|
| Lo, your wish is granted! You can most definitely split points between multiple answers. If you care to, you can request moderation on this question to split the points or re-open the question, even though it's closed. Although I'm sure VGR appreciates the points... ;-) |
|||
| By: VGR | Date: 01/10/2003 04:48:00 | Type : Comment |
|
| who, me ? :D well, "what's done is done" :D |
|||
|
Do register to be able to answer |
|||
©2012 These pages are served without commercial sponsorship. (No popup ads, etc...). Bandwidth abuse increases hosting cost forcing sponsorship or shutdown. This server aggressively defends against automated copying for any reason including offline viewing, duplication, etc... Please respect this requirement and DO NOT RIP THIS SITE.
Please DO link to this page!








