Home > Net >  How to sort an multidimensional by decision inside an item
How to sort an multidimensional by decision inside an item

Time:11-03

I'm trying to sort my array correctly. I want to sort it depending on the "recipient" entry. While every iteration of the sorting process PHP should check if it should sort the next item by userName or by locationName.

It should be one sorting process.

The nulls should get attached at the end of the output.

// ARRAY TO SORT

$array =    [    
[  
    "id"           =>  1,  
    "recipient"    => "User",
    "userName"     => "Max Mustermann",
    "locationName" => "Test Location"
],      
[  
    "id"           =>  2,  
    "recipient"    => "Location",
    "userName"     => "Susi Mustermann",
    "locationName" => "Another Location"
],     
[  
    "id"           =>  3,  
    "recipient"    => "Location",
    "userName"     => "Susi Mustermann",
    "locationName" => "Wow Much Location"
],     
[  
    "id"           =>  4,  
    "recipient"    => "User",
    "userName"     => "Fritz Kalkbrenner",
    "locationName" => "Good Music"
],     
[  
    "id"           =>  5,  
    "recipient"    => "Location",
    "userName"     => "Paul Kalkbrenner",
    "locationName" => null
],  
];

It's hard for me to find the correct title for that question. Is there a way doing it in one process or should I split the array and sort them one by one?

CodePudding user response:

It must be sorted according to 3 criteria:

  1. by recipient
  2. locationName !== null
  3. by userName or locationName depending on the recipient

In order to avoid the case distinction, the correct key is generated in advance by concatenation.

usort($array,function($a,$b){
  $sort2key = strtolower($a['recipient']).'Name';
  return $a['recipient'] <=> $b['recipient']
  ?: is_null($a['locationName']) <=> is_null($b['locationName'])
  ?: $a[$sort2key] <=> $b[$sort2key];
});

Demo: https://3v4l.org/L6cBn

  • Related