rahul
rahul

Reputation: 849

sort multi dimensional array by a value based on order given in another multidimensional array in php

I have two multi dimensional arrays here:- one which is having the order

$order = [1=>'apple', 2=>'banana', 3=>'mango'];

Another array in which i have the data to be sorted:

$data = [
['title'=>'fruit', 'name'=>'banana'],
['title'=>'fruit', 'name'=>'apple'],
['title'=>'fruit', 'name'=>'mango'],
['title'=>'fruit', 'name'=>'pineapple'],
];

There are values whose order in not mentioned in the $order array so they can come underneath the rest of the array values as given in the result below:

After sorting i should be getting the result as :

[
    ['title'=>'fruit', 'name'=>'apple'],
    ['title'=>'fruit', 'name'=>'banana'],
    ['title'=>'fruit', 'name'=>'mango'],
    ['title'=>'fruit', 'name'=>'pineapple']
];

I have gone through many answers in SO but couldn't even begin with such a scenario; 1. How do I Sort a Multidimensional Array in PHP 2. Sort PHP multi-dimensional array based on value in inner array?

Upvotes: 0

Views: 39

Answers (2)

Ghlen
Ghlen

Reputation: 659

first, flip the array:

$order = array_flip($order);

Then simply use usort to fix it:

usort($data, static function(array $x, array $y) use ($order) {
    return $order[$x['name']] - $order[$y['name']];
})

Upvotes: 1

jspit
jspit

Reputation: 7683

$order = [1=>'apple', 2=>'banana', 3=>'mango'];

$data = [
['title'=>'fruit', 'name'=>'banana'],
['title'=>'fruit', 'name'=>'apple'],
['title'=>'fruit', 'name'=>'mango'],
['title'=>'fruit', 'name'=>'pineapple'],
];

usort($data,function($a,$b) use($order){
  $ka = array_search($a['name'],$order);
  $kb = array_search($b['name'],$order);
  if($ka === false) $ka=9999;
  if($kb === false) $kb=9999;
  return $ka <=> $kb;
});

Result:

array (
  0 => 
  array (
    'title' => "fruit",
    'name' => "apple",
  ),
  1 => 
  array (
    'title' => "fruit",
    'name' => "banana",
  ),
  2 => 
  array (
    'title' => "fruit",
    'name' => "mango",
  ),
  3 => 
  array (
    'title' => "fruit",
    'name' => "pineapple",
  ),
)

Upvotes: 1

Related Questions