# php对二维数组排序

85 次浏览
###### 排序前
``````\$arr = array(
'apple' => array('weight'=>'3'),
'orange' => array('weight'=>'5'),
'banana' => array('weight'=>'2'),
'tomato' => array('weight'=>'1'),
);``````
###### 排序后(根据weight排序)
``?``

Dyan 235
12月3日提问
3 个回答

``````\$arr = [
['name' => 'apple', 'weight' => '3'],
['name' => 'orange', 'weight' => '5'],
['name' => 'banana', 'weight' => '2'],
['name' => 'tomato', 'weight' => '1'],
];

usort(\$arr, function (\$current, \$next): int {
return \$current['weight'] > \$next['weight'] ? 1 : -1;
});

var_dump(\$arr);``````
1

/**

• @desc arraySort php二维数组排序 按照指定的key 对数组进行自然排序
• @param array \$arr 将要排序的数组
• @param string \$keys 指定排序的key
• @param string \$type 排序类型 asc | desc
• @return array

*/
function arraySort(\$arr, \$keys, \$type = 'asc')
{

``````\$keysvalue = \$new_array = array();
foreach (\$arr as \$k => \$v) {
\$keysvalue[\$k] = \$v[\$keys];
}
if (\$type == 'asc') {
natsort(\$keysvalue);
}
if (\$type == 'desc') {
natsort(\$keysvalue);
// 将原数组中的元素顺序翻转,如果第二个参数指定为 true，则元素的键名保持不变
\$keysvalue = array_reverse(\$keysvalue, TRUE);
}
foreach (\$keysvalue as \$k => \$v) {
\$new_array[\$k] = \$arr[\$k];
}
return \$new_array;``````

}
\$arr = arraySort(\$arr, "weight", "asc" );
var_dump(\$arr);

``````\$arr = array(
'apple' => array('weight'=>'3'),
'orange' => array('weight'=>'5'),
'banana' => array('weight'=>'2'),
'tomato' => array('weight'=>'1'),
);
\$weight = array_column(\$arr, 'weight');
array_multisort(\$weight, SORT_ASC, \$arr);
var_dump(\$arr);``````