Home > Back-end >  How to order a php array based on custom value
How to order a php array based on custom value

Time:01-05

I have the following php array:

array(4) {
  [0]=>
  array(3) {
    ["POSITION"]=>
    string(6) "Marketer"
    ["FIRSTNAME"]=>
    string(7) "John1"
    ["EMAIL"]=>
    string(13) "[email protected]"
  }
  [1]=>
  array(3) {
    ["POSITION"]=>
    string(10) "Designer"
    ["FIRSTNAME"]=>
    string(6) "John2"
    ["EMAIL"]=>
    string(29) "[email protected]"
  }
  [2]=>
  array(3) {
    ["POSITION"]=>
    string(7) "CEO"
    ["FIRSTNAME"]=>
    string(6) "John3"
    ["EMAIL"]=>
    string(21) "[email protected]"
  }
  [3]=>
  array(3) {
    ["POSITION"]=>
    string(10) "Developer"
    ["FIRSTNAME"]=>
    string(5) "John4"
    ["EMAIL"]=>
    string(25) "[email protected]"
  }
}

I want to reorder it based on [POSITION] column as follows:

  1. CEO
  2. Marketer
  3. Developer
  4. Designer

How can I do this? Any help would be highly appreciated.

Thanks

CodePudding user response:

Put the positions in an array, then use this in the comparison function in usort().

$positions = [
    'CEO' => 1,
    'Marketer' => 2,
    'Developer' => 3,
    'Designer' => 4
];

usort($array, function($a, $b) use ($positions) {
    return $positions[$a['POSITION']] - $positions[$b['POSITION']];
})
  • Related