Wednesday, 29 August 2018

Sorting arrays based on another index value in PHP


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.

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"
}

0 comments:

Post a Comment