Jump to content

help with sorting a 2D array


MogenUggla

Recommended Posts

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.

Link to comment
https://forums.phpfreaks.com/topic/229104-help-with-sorting-a-2d-array/
Share on other sites

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?

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.