Skip to content

Instantly share code, notes, and snippets.

@svdmitrij
Last active August 29, 2015 14:14
Show Gist options
  • Save svdmitrij/23df8884b330562f212f to your computer and use it in GitHub Desktop.
Save svdmitrij/23df8884b330562f212f to your computer and use it in GitHub Desktop.
Function sorting array of arrays by value one of fields
<?php
function sort_array_by_key($params)
{
$sort_orders = array('asc' => SORT_ASC, 'desc' => SORT_DESC);
$sort_order = $sort_orders[$params['order']];
$field = $params['key'];
$array = $params['array'];
$field_array = array();
foreach ($array as $key => $row)
{
$field_array[$key] = $row[$field];
}
array_multisort($field_array, $sort_order, $array);
return $array;
}
$array = [['a' => 10, 'b' => 723],['a' => 52, 'b' => 323],['a' => 65, 'b' => 577]];
$sorted_array = sort_array_by_key(['array' => $array, 'key' => 'b', 'order' => 'asc']);
print_r($sorted_array);
[['a' => 52, 'b' => 323], ['a' => 65, 'b' => 577], ['a' => 10, 'b' => 723]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment