[英]Sorting array according to the values in PHP
I have the following array 我有以下数组
[0] => Array
(
[id] => 229
[val] => 2
)
[3] => Array
(
[id] => 237
[val] => 1
)
[4] => Array
(
[id] => 238
[val] => 6
)
I need to sort this array according to the val values in the array, and do not know how to accomplish this? 我需要根据数组中的val值对这个数组进行排序,不知道如何实现这个目的?
array_multisort可以帮助解决这个问题,例3给出了类似的问题和解决方案。
You can use array_multisort()
你可以使用
array_multisort()
Examples here: http://www.php.net/manual/en/function.array-multisort.php 例如: http : //www.php.net/manual/en/function.array-multisort.php
The Example #3 Sorting database results is what you want. 示例#3排序数据库结果是您想要的。 Might be easier if you are not familiar with callback functions and
usort()
. 如果您不熟悉回调函数和
usort()
可能会更容易。
function sksort(&$array, $subkey="id",$sort_ascending=false)
{
if (count($array))
$temp_array[key($array)] = array_shift($array);
foreach($array as $key => $val){
$offset = 0;
$found = false;
foreach($temp_array as $tmp_key => $tmp_val)
{
if(!$found and strtolower($val[$subkey]) > strtolower($tmp_val[$subkey]))
{
$temp_array = array_merge(
(array)array_slice($temp_array,0,$offset),
array($key => $val),
array_slice($temp_array,$offset)
);
$found = true;
}
$offset++;
}
if(!$found) $temp_array = array_merge($temp_array, array($key => $val));
}
if ($sort_ascending) $array = array_reverse($temp_array);
else $array = $temp_array;
}
========================================================================== now use this function in ur array ================================================== ========================现在在你的数组中使用这个函数
sksort($arrayname, "val"); /* for ascending */
sksort($arrayname, "val", true); /* for descending */
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.