crookedbonsai
6/5/2017 - 12:24 PM

Sort multidimensional Array by specific key

Sort multidimensional Array by specific key


// Example Array
$array = [
  'name' => 'Steve', 'age' => 20
  'name' => 'Bob',   'age' => 50
];

// usort callback function
protected function sortByName($a, $b)
{
    $a = $a['name'];
    $b = $b['name'];

    if ($a == $b)
    {
        return 0;
    }

    return ($a < $b) ? -1 : 1;
}

// Command to sort array
$sortedArray = usort($array, 'sortByName');