0

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?

rahul
  • 841
  • 1
  • 8
  • 18

2 Answers2

1

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']];
})
rahul
  • 841
  • 1
  • 8
  • 18
Ghlen
  • 659
  • 4
  • 14
  • usort($data it should be and i'm getting an error undefined index pineapple – rahul Apr 02 '20 at 12:39
  • That's because you don't have pinneaple in your order array. Simply add it :) You could also use a failsafe in case you don't have the index by accessing $x and $y with a null coalesce operator: $x['name'] ?? count($order) this essentialy makes it so an undefined index in your order will automatically be placed last – Ghlen Apr 02 '20 at 12:43
  • what if name is null – rahul Apr 02 '20 at 12:45
  • 1
    You need to know in your application in what form the incoming data will be. If the name is null, or the index is undefined, you need to account for that. If you want to make null names to be placed in the front, you can make your order array like this [0 => null, 1 => 'apple', ...] etc. – Ghlen Apr 02 '20 at 12:48
1
$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",
  ),
)
jspit
  • 7,276
  • 1
  • 9
  • 17