/**
* 二维数组按照指定的键值进行排序
* @param string $arr 数组
* @param string $keys 排序key
* @param string $type 排序方式
* @return array
*/
function array_sort($arr, $keys, $type = 'asc')
{
$keysvalue = $new_array = array();
foreach ($arr as $k => $v) {
$keysvalue[$k] = $v[$keys];
}
if ($type == 'asc') {
asort($keysvalue);
} else {
arsort($keysvalue);
}
reset($keysvalue);
foreach ($keysvalue as $k => $v) {
$new_array[$k] = $arr[$k];
}
return $new_array;
}
使用实例
$array = [
['name' => '手机', 'brand' => '诺基亚', 'price' => 1050],
['name' => '笔记本电脑', 'brand' => 'lenovo', 'price' => 4300],
['name' => '剃须刀', 'brand' => '飞利浦', 'price' => 3100],
['name' => '跑步机', 'brand' => '三和松石', 'price' => 4900],
['name' => '手表', 'brand' => '卡西欧', 'price' => 960],
['name' => '液晶电视', 'brand' => '索尼', 'price' => 6299],
['name' => '激光打印机', 'brand' => '惠普', 'price' => 1200],
];
$list = array_sort($array, 'price');
print_r($list);
结果
Array
(
[4] => Array
(
[name] => 手表
[brand] => 卡西欧
[price] => 960
)
[0] => Array
(
[name] => 手机
[brand] => 诺基亚
[price] => 1050
)
[6] => Array
(
[name] => 激光打印机
[brand] => 惠普
[price] => 1200
)
[2] => Array
(
[name] => 剃须刀
[brand] => 飞利浦
[price] => 3100
)
[1] => Array
(
[name] => 笔记本电脑
[brand] => lenovo
[price] => 4300
)
[3] => Array
(
[name] => 跑步机
[brand] => 三和松石
[price] => 4900
)
[5] => Array
(
[name] => 液晶电视
[brand] => 索尼
[price] => 6299
)
)
非特殊说明,本博所有文章均为博主原创。
如若转载,请注明出处:https://www.ihulang.com/index/info/5.html