基于php中另一个索引值的数组排序

时间:2014-05-20 12:23:05

标签: php arrays sorting

我有两个数组:

$number=array(1212,340,2310,670,90);            
$cars=array("Volvo","BMW","Toyota","Maruti","Zen");

我需要将$number数组从高到低排序,我正在使用rsort进行排序。我想根据$cars的排序索引值对$numbers进行排序并回显它。像:

$number=array(2310,1212,670,340,90); //sorted values
$cars=array("Toyota","Volvo","Maruti","BMW","Zen") //then display these values

我想我需要使用此答案Sort an Array by keys based on another Array?中提到的$order,但我仍然无法弄明白。我不想合并两个阵列。我想基于其他数组的n索引值对数组进行排序。

3 个答案:

答案 0 :(得分:0)

一个简单的multisort应该:

$number=array(1212,340,2310,670,90);
$cars=array("Volvo","BMW","Toyota","Maruti","Zen");

array_multisort($number, SORT_DESC, SORT_NUMERIC, $cars);

var_dump($cars);

完全按照您的意愿输出:

array(5) {
  [0]=>
  string(6) "Toyota"
  [1]=>
  string(5) "Volvo"
  [2]=>
  string(6) "Maruti"
  [3]=>
  string(3) "BMW"
  [4]=>
  string(3) "Zen"
}

答案 1 :(得分:-1)

您需要array_combine ...

以下是一个例子:

<?php
    $number=array(1212,340,2310,670,90);            
    $cars=array("Volvo","BMW","Toyota","Maruti","Zen");
    $newarray = array_combine($number, $cars);

    print_r($newarray);
?>

结果:

Array ( [1212] => Volvo [340] => BMW [2310] => Toyota [670] => Maruti [90] => Zen ) 

http://www.php.net/manual/en/function.array-combine.php

答案 2 :(得分:-1)

使用多维数组,然后对其进行排序:

<?php        
$cars=array(1212=>"Volvo",340=>"BMW",2310=>"Toyota",670=>"Maruti",90=>"Zen");
krsort($cars);
foreach ($cars as $key => $val) {
echo "$key = $val\n";
}