Skip to main content

Posts

Showing posts from February, 2019

Function to sort multi dimensional array based on column from child array (PHP)

Sometimes we need the ability to sort an array depending on the value of column from child array. Below method will allow you to get it done. /*  * Generic multi dimensional array sorter  * Requires PHP 7.x for the spaceship operators  */  function sortData(&$data, $datakey, $sortOrder = 'asc')  {      function generic_sorter($datakey, $sortOrder)      {          return function ($a, $b) use ($datakey, $sortOrder) {              return ($sortOrder  == 'desc') ? ($b[$datakey] <=> $a[$datakey])              : ($a[$datakey] <=> $b[$datakey]);          };      }          $datakey = strtolower(trim($datakey));      $sortOrder = strtolower(trim($sortOrder));      $firstArr = reset($data);      if...