How to sort multi-dimensional array (PHP)?
How to sort this array by pos
attribute even though keys (name,开发者_StackOverflow中文版 store_id, product etc.
)
[Attributes] => Array
(
[name] => Array
(
[pos] => 30
)
[store_id] => Array
(
[pos] => 10
)
[product] => Array
(
[pos] => 20
)
)
Edit: performance is important of course.
You could use uasort()
which lets you define your sorting logic and also maintains your associative indexes. Please note that it changes your original array and only returns a boolean based on success.
uasort($your_array, function($a, $b) {
return $a['pos'] > $b['pos'];
});
My example works >= PHP 5.3 , but for older versions you can use a normal compare function as well.
See uasort()
Documentation for details.
Have a look at the PHP function array_multisort
.
http://php.net/manual/en/function.array-multisort.php
There is an example-function in the comments, which should be fine for you:
function array_orderby()
{
$args = func_get_args();
$data = array_shift($args);
foreach ($args as $n => $field) {
if (is_string($field)) {
$tmp = array();
foreach ($data as $key => $row)
$tmp[$key] = $row[$field];
$args[$n] = $tmp;
}
}
$args[] = &$data;
call_user_func_array('array_multisort', $args);
return array_pop($args);
}
// $dataArray is the array that contains your data
$sorted = array_orderby($dataArray, 'pos', SORT_DESC);
精彩评论