Skip to content

Instantly share code, notes, and snippets.

@richjenks
Created November 6, 2014 12:11
Show Gist options
  • Save richjenks/2ea25ce7b12306a86943 to your computer and use it in GitHub Desktop.
Save richjenks/2ea25ce7b12306a86943 to your computer and use it in GitHub Desktop.
<?php
/**
* sort_arr_by_key
*
* Sorts a given array by the values of its child arrays
*
* The code below would order the array items by age:
*
* <code>
* $array = array(
* array(
* 'name' => 'jim',
* 'age' => 30,
* ),
* array(
* 'name' => 'rob',
* 'age' => 25,
* ),
* );
* var_dump($array, 'age');
* </code>
*
* @param array $sort_array The array being sorted
* @param string $sort_key The key to sort by
*
* @return array The sorted array
*/
public static function sort_arr_by_key($sort_array, $sort_key) {
// Declare array to prevent aray_multisort throwing error if $sort_array is empty
$values = array();
// Populate array for the "column" being sorted
foreach ($sort_array as $key => $row) {
$values[$key] = $row[$sort_key];
}
// Sort the array naturally and case-insensitively
array_multisort($values, SORT_FLAG_CASE | SORT_NATURAL, $sort_array);
return $sort_array;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment