30 seconds of PHP

  Back to Home

orderBy

arrayadvanced

Sorts a collection of arrays or objects by key.

Uses sort() on the provided array to sort the array based on $order and $attr.

function orderBy($items, $attr, $order)
{
  $sortedItems = [];
  foreach ($items as $item) {
    $key = is_object($item) ? $item->{$attr} : $item[$attr];
    $sortedItems[$key] = $item;
  }
  if ($order === 'desc') {
    krsort($sortedItems);
  } else {
    ksort($sortedItems);
  }

  return array_values($sortedItems);
}