0

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?

Florianb
  • 166
  • 2
  • 12

1 Answers1

1

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

jspit
  • 7,276
  • 1
  • 9
  • 17
  • Thank you! You saved my day! Was trying to do it with usort, but I wasn't able to manage it. One last thing. How can I transfer all NULLs to the end of the array, so only sorted users and locations are on the top and the nulls on the end? – Florianb Nov 02 '22 at 20:22
  • Which fields can be null and should be taken into account? Data reflecting the problem and the expected result of it would be helpful. Please complete the question accordingly. – jspit Nov 03 '22 at 07:11