3

I have two different arrays. One array, a, for a list of people. My other array, b, for a list of their ages. I go to sort b by number and then reverse it so it goes in descending order. I got to this part okay.

How do I sort a (a list of people's names) so that the same values are still paired up with the sorted list?

Example:

a contains Bob, Sue, Phil, and Jenny respectively

b contains 15, 12, 13, and 13 respectively.

I want my outcome to be:

a contains Bob, Jenny, Phil, and Sue respectively

b contains 15, 13, 13, and 12 respectively

1

2 Answers 2

10

http://php.net/manual/en/function.array-multisort.php

using example #1 in the reference:

$a = array('Bob', 'Sue', 'Phil', 'Jenny');
$b = array(15, 12, 13, 13);
array_multisort($a, $b);
print_r($a);
> Array
 (
 [0] => Bob
 [1] => Jenny
 [2] => Phil
 [3] => Sue
 )
print_r($b);
> Array
 (
 [0] => 15
 [1] => 13
 [2] => 13
 [3] => 12
 )
Sign up to request clarification or add additional context in comments.

2 Comments

bfavaretto answer would be the great answer for me if he really wants the two array to be combine and match up with their correct ages.
@MarCejas, agreed, but the answer is yours, I just added an example :)
5

Why not just use:

$arr = array('Bob'=>15,'Sue'=>12,'Phil'=>13,'Jenny'=>13);

Then you can sort smoothly.

3 Comments

Example: $c = array_combine($a, $b); asort($c);
having array structured this way will also make it simple and scalable. On this structure you can reverse the array php.net/manual/en/function.rsort.php or sort the array php.net/manual/en/function.ksort.php using php functions and not worry abt how to reflect the changes to your other aray
What if you have two Jennys?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.