MogenUggla Posted February 28, 2011 Share Posted February 28, 2011 Hello! I have a 2D array that look as follows: $test["name"][0] = "arnold"; $test["name"][1] = "nate"; $test["name"][2] = "steve"; $test["id"][0] = 2; $test["id"][1] = 0; $test["id"][2] = 1; This means arnold has an ID of 2, nate has an ID of 0 and steve has an ID of 1. Now I want to sort the array based on the ID value, so I want to achieve the following result: $test["name"][0] = "nate"; $test["name"][1] = "steve"; $test["name"][2] = "arnold"; How would I achieve this? Help much appreciated. Quote Link to comment Share on other sites More sharing options...
requinix Posted February 28, 2011 Share Posted February 28, 2011 array_multisort is your friend. Quote Link to comment Share on other sites More sharing options...
MogenUggla Posted February 28, 2011 Author Share Posted February 28, 2011 I have tried but the results are not satisfying. It only works if I have "name" and "ID" but if I have more fields such as "age" they will loose their associativity. $test["name"][0] = "arnold"; $test["name"][1] = "nate"; $test["name"][2] = "steve"; $test["id"][0] = 2; $test["id"][1] = 0; $test["id"][2] = 1; $test["age"][0] = 24; $test["age"][1] = 28; $test["age"][2] = 17; //=================================== echo "<br> id: " .$test["id"][0]. " name: " . $test["name"][0] . " age: " . $test["age"][0]; echo "<br> id: " .$test["id"][1]. " name: " . $test["name"][1] . " age: " . $test["age"][1]; echo "<br> id: " .$test["id"][2]. " name: " . $test["name"][2] . " age: " . $test["age"][2]; array_multisort($test["id"], SORT_ASC, SORT_STRING, $test["name"], SORT_NUMERIC, SORT_DESC); echo "<br>"; echo "<br> id: " .$test["id"][0]. " name: " . $test["name"][0] . " age: " . $test["age"][0]; echo "<br> id: " .$test["id"][1]. " name: " . $test["name"][1] . " age: " . $test["age"][1]; echo "<br> id: " .$test["id"][2]. " name: " . $test["name"][2] . " age: " . $test["age"][2]; result: id: 2 name: arnold age: 24 id: 0 name: nate age: 28 id: 1 name: steve age: 17 id: 0 name: nate age: 24 <- wrong id: 1 name: steve age: 28 <- wrong id: 2 name: arnold age: 17 <- wrong What am I doing wrong? Quote Link to comment Share on other sites More sharing options...
MogenUggla Posted February 28, 2011 Author Share Posted February 28, 2011 I solved the problem by doing it with a while-loop. $i = 0; while($i< 3) { $id = $test["id"][$i]; $newtest["name"][$id] = $test["name"][$i]; $newtest["age"][$id] = $test["age"][$i]; $newtest["id"][$id] = $test["id"][$i]; $i++; } Quote Link to comment Share on other sites More sharing options...
AbraCadaver Posted February 28, 2011 Share Posted February 28, 2011 array_multisort($test["id"], $test["name"], $test["age"]); 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.