Tuesday, 28 August 2018

PHP-Sort array based on another array?


OK, I already got this question in stackoverflow but sadly it's in javascript - Javascript - sort array based on another array


and I want it in PHP
$data = array(
   "item1"=>"1",
   "item2"=>"3",
   "item3"=>"5",
   "item4"=>"2",
   "item5"=>"4"
);

to match the arrangement of this array:
sortingArr = array("5","4","3","2","1");

and the output I'm looking for:
$data = array(
    "item3"=>"5",
    "item5"=>"4",
    "item2"=>"3",
    "item4"=>"2",
    "item1"=>"1"
 );

Any idea how this can be done? Thanks.

Pretty simple ?
$data = array(
   "item1"=>"1",
   "item2"=>"3",
   "item3"=>"5",
   "item4"=>"2",
   "item5"=>"4"
);

$sortingArr = array("5","4","3","2","1");

$result = array(); // result array
foreach($sortingArr as $val){ // loop
    $result[array_search($val, $data)] = $val; // adding values
}
print_r($result); // print results

Output:
Array
(
    [item3] => 5
    [item5] => 4
    [item2] => 3
    [item4] => 2
    [item1] => 1
)

0 comments:

Post a Comment