0

I have two arrays:

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

I need to sort $number array from high to low, which I am doing using rsort. I want to sort $cars based on sorted index value of $numbers and echo it. Like:

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

I guess I need to use $order as mentioned in this answer Sort an Array by keys based on another Array? but I am still not able to figure out. I don't want to combine the 2 arrays. I want to sort an array based n index value of other array.

Community
  • 1
  • 1
user2567857
  • 483
  • 7
  • 25
  • First merge the arrays so that first array becomes the key and second array becomes respective values for the new array, then sort them based on keys – hjpotter92 May 20 '14 at 12:25
  • There is no direct correlation between those two arrays, and therefore there is no way for you to establish a relationship between the two arrays unless you start using indices. Basically what @hjpotter92 said. – Ohgodwhy May 20 '14 at 12:25

3 Answers3

0

A simple multisort should to it:

$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);

Output exactly as you want it:

array(5) {
  [0]=>
  string(6) "Toyota"
  [1]=>
  string(5) "Volvo"
  [2]=>
  string(6) "Maruti"
  [3]=>
  string(3) "BMW"
  [4]=>
  string(3) "Zen"
}
Gerald Schneider
  • 17,416
  • 9
  • 60
  • 78
-1

You need array_combine...

Here's an example:

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

    print_r($newarray);
?>

results in:

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

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

Joran Den Houting
  • 3,149
  • 3
  • 21
  • 51
-1

Use a multidimensional array and then Sort it:

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