PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!
Moderator: General Moderators
pgolovko
Forum Commoner
Posts: 38 Joined: Sun Sep 17, 2006 9:13 am
Post
by pgolovko » Sun Dec 03, 2006 10:28 pm
I broke my head rethinking this loginc. I need to sont a multi-dimensional array by specific field. This is my array:
Code: Select all
[info] => Array
(
[1] => Array
(
[title] => Boss
[rank] => 7
)
[2] => Array
(
[title] => Angel
[rank] => 6
)
[3] => Array
(
[title] => Rat
[rank] => 1
)
[4] => Array
(
[title] => Demon
[rank] => 4
)
[5] => Array
(
[title] => Soldier
[rank] => 5
)
)
What I need this to be is:
Code: Select all
[info] => Array
(
[1] => Array
(
[title] => Rat
[rank] => 1
)
[2] => Array
(
[title] => Demon
[rank] => 4
)
[3] => Array
(
[title] => Soldier
[rank] => 5
)
[4] => Array
(
[title] => Angel
[rank] => 6
)
[5] => Array
(
[title] => Boss
[rank] => 7
)
)
I guess I need to use
http://www.php.net/manual/en/function.a ... tisort.php but I cant get it to sort the thing. I'd really appreciate any help here.
feyd
Neighborhood Spidermoddy
Posts: 31559 Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA
Post
by feyd » Sun Dec 03, 2006 10:40 pm
What have you tried?
pgolovko
Forum Commoner
Posts: 38 Joined: Sun Sep 17, 2006 9:13 am
Post
by pgolovko » Sun Dec 03, 2006 10:55 pm
Code: Select all
for ($a = 1; $a <= count($arr["info"]); $a++){
array_multisort($arr["info"][$a]);
}
Do you think you could correct my code?
pgolovko
Forum Commoner
Posts: 38 Joined: Sun Sep 17, 2006 9:13 am
Post
by pgolovko » Mon Dec 04, 2006 3:56 am
Works, but not exactly. Code:
Code: Select all
<?php
function cmp($a, $b)
{
return strcmp($a["fruit"], $b["fruit"]);
}
$fruits[0]["fruit"] = "1";
$fruits[1]["fruit"] = "7";
$fruits[2]["fruit"] = "10";
$fruits[3]["fruit"] = "6";
$fruits[4]["fruit"] = "5";
$fruits[5]["fruit"] = "0";
usort($fruits, "cmp");
while (list($key, $value) = each($fruits)) {
echo "\$fruits[$key]: " . $value["fruit"] . "<br>\n";
}
?>
Will return:
Code: Select all
$fruits[0]: 0
$fruits[1]: 1
$fruits[2]: 10
$fruits[3]: 5
$fruits[4]: 6
$fruits[5]: 7
Where I need it to return:
Code: Select all
$fruits[0]: 0
$fruits[1]: 1
$fruits[2]: 5
$fruits[3]: 6
$fruits[4]: 7
$fruits[5]: 10
volka
DevNet Evangelist
Posts: 8391 Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger
Post
by volka » Mon Dec 04, 2006 3:59 am
You're using a string function but you compare numbers.
Code: Select all
function cmp($a, $b)
{
$a = (int)$a["fruit"];
$b = (int)$b["fruit"];
if ( $a < $b )
return -1;
else if if ( $a == $b )
return 0;
else
return 1;
}
pgolovko
Forum Commoner
Posts: 38 Joined: Sun Sep 17, 2006 9:13 am
Post
by pgolovko » Mon Dec 04, 2006 4:12 am
Yup, thats it.
Thanks volka!