多维数组如何根据指定键值?比如现在有数组结构如下:
$data = array(
0 => array('name' => '1班','avgScore'=>90,'subject' => 'math'),
1 => array('name' => '2班','avgScore'=>60,'subject' => 'math'),
2 => array('name' => '3班','avgScore'=>88,'subject' => 'math' ),
);
如何把它变成:
$data = array(
0 => array('name' => '1班','avgScore'=>90,'subject' => 'math'),
1 => array('name' => '3班','avgScore'=>88,'subject' => 'math'),
2 => array('name' => '2班','avgScore'=>60,'subject' => 'math'),
);
1、array_multisort()
可使用 array_multisort()函数排序,
function mySort($arr = array(),$sort_by){
foreach($arr as $k => $v){
$avgScore[$k] = $v[$sort_by];
}
array_multisort($avgScore, SORT_DESC, $arr);
return $arr;
}
echo "<pre>";
print_r(mySort($data),'avgScore');
输出:
$data = array(
0 => array('name' => '1班','avgScore'=>90,'subject' => 'math'),
1 => array('name' => '3班','avgScore'=>88,'subject' => 'math'),
2 => array('name' => '2班','avgScore'=>60,'subject' => 'math'),
);