PHP - Sort Two Arrays The Same Way

情到浓时终转凉″ 提交于 2019-12-10 10:47:10

问题


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:


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
 )



回答2:


Why not just use:

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

Then you can sort smoothly.



来源:https://stackoverflow.com/questions/9917864/php-sort-two-arrays-the-same-way

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!