visitor (0 QPoints)
  • FR
  • EN
  • NL
  • DE
  • ES
316 experts, 1194 registered users, 1659 questions already answered
European Experts Exchange, the very best site for high-quality IT solutions

New Improved Search!

 


05/10/2011 1h30 : Steve Jobs is dead, the father of Apple ][ is gone, we are all orphaned.

Languages :: PHP :: Sorting multidimensional array


By: PHP newbee U.S.A.  Date: 01/10/2003 00:00:00  English  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 English  Type : Comment
Might it be that the number is a string?
By: VGR Date: 01/10/2003 00:26:00 English  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 English  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 English  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 English  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 English  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 English  Type : Comment
who, me ? :D

well, "what's done is done" :D

Do register to be able to answer

EContact
browser fav
page generated in 362.740040 milliseconds

Why Google AdSense ads ?

compteur
 Ranking-Hits PageRank for this page