Search code examples
phparrayssortingmultidimensional-arraycustom-sort

Sorting 2-D associative array and categorizing on basis of a key value


I'm a newbie here. Have a question about a php sorting thing. Have searched a lot, but unfortunately couldn't find a solution to what I was searching. I know it's easy -- but I don't know why I couldn't find it after searching for hours.

I've an array like this. They have a key "duty" , I want to do some kind of Sorting on this so that the new array contains - arrays inorder with the "duty" field.

$arrayName = array(
array(
    'name' => 'Dr. Hugo Lopez',
    'duty' => 'Anesthesiologist',
    'link' => ''
),
array(
    'name' => 'Dr. Dario Garin',
    'duty' => 'Orthopedic Specialist',
    'link' => 'dr-dario-garin.php'
),
array(
    'name' => 'Dr. Maclovio Yañez',
    'duty' => 'Plastic Surgeon',
    'link' => ''
),
array(
    'name' => 'Melissa Bracker',
    'duty' => 'Patient Liaison',
    'link' => ''
),
array(
    'name' => 'Dr. Diego Guzman',
    'duty' => 'Cardiologist',
    'link' => ''
),
array(
    'name' => 'Ivan Arafat',
    'duty' => 'Accountant',
    'link' => ''
),
array(
    'img-old' => 'jorge-fernandez.jpg',
    'duty' => 'Hospital Administrator',
    'link' => ''
),
);

I tried:

usort($arrayName, function($a, $b) {
return $a['duty'] - $b['duty'];
});

But this arranges the array in descending order of the Duty field.

I want to arrange it in order with a priority on Duty field. Like : I will set the order of Duty field values to arrange them in categories of Nurse, Maintenance, Doctors, Drivers and etc.

I want to be able to - set the order of categorization by myself using some sort of array.

sort($arrayName, $priority);
$priority = array( 'President', 'Vice President', 'Doctors', 'Nurse', 'Maintenance', 'Drivers');

I'm not much familiar to PHP. Pardon if I am asking basic questions.


Solution

  • Here is my solution, not the most efficient but it should do the trick, and it should account for the issue of a duty not defined as a priority.

    $priority = array('Orthopedic Specialist', 'Hospital Administrator', 'Accountant', 'Anesthesiologist', 'Plastic Surgeon');
    
    function dutySort(array &$array, array $priority) {
    
        usort($array, function($a, $b) use ($priority) {
            $aPriority = array_search($a['duty'], $priority);
            $aPriority = ($aPriority !== false ? $aPriority : count($priority));
            $bPriority = array_search($b['duty'], $priority);
            $bPriority = ($bPriority !== false ? $bPriority : count($priority));
    
            return ($aPriority < $bPriority) ? -1 : 1;
        });
    }
    
    dutySort($array, $priority);