Posted in PHP onMay 02, 2017
今天发现一个很好用二维数组排序的php方法,usort,推荐给大家,以后二维数组里面,要按照一个字段的值排序用这个方法简单高效,例如下面的数组:
[guess_subject] => Array ( [0] => Array ( [subject_id] => 4587 [game_id] => 9228 [parent_category_id] => 78 [subject_title] => 全场比赛两队总得分之和是 [subject_date_time] => 1490668200 [status] => 2 [subject_answer] => 0 [totle_join] => 0 [max_nickname] => [max_currency] => ) [1] => Array ( [subject_id] => 4588 [game_id] => 9228 [parent_category_id] => 78 [subject_title] => 本场比赛是否有加时赛 [subject_date_time] => 1490668200 [status] => 2 [subject_answer] => 0 [totle_join] => 0 [max_nickname] => [max_currency] => ) [2] => Array ( [subject_id] => 4584 [game_id] => 9228 [parent_category_id] => 78 [subject_title] => 第二节两队总得分之和是 [subject_date_time] => 1490668200 [status] => 1 [subject_answer] => 0 [totle_join] => 0 [max_nickname] => [max_currency] => ) [3] => Array ( [subject_id] => 4585 [game_id] => 9228 [parent_category_id] => 78 [subject_title] => 第三节两队总得分之和是 [subject_date_time] => 1490668200 [status] => 2 [subject_answer] => 0 [totle_join] => 0 [max_nickname] => [max_currency] => ) )
要按照status字段的升序排列的话,只需要这样写
foreach($data as $key => &$value) { // 按照status的升序排序,使用用户自定义的比较函数对数组中的值进行排序, // 本函数将用用户自定义的比较函数对一个数组中的值进行排序。 如果要排序的数组需要用一种不寻常的标准进行排序,那么应该使用此函数。 // 在第一个参数小于,等于或大于第二个参数时,该比较函数必须相应地返回一个小于,等于或大于 0 的整数。 usort($value['guess_subject'], function($a, $b){ if ($a['status'] == $b['status']) return 0; return ($a['status'] < $b['status']) ? -1 : 1; }); } return $data;
就会按照status的 升序排列啦, status=1 的数组单元会排在前面
php usort 使用用户自定义的比较函数对二维数组中的值进行排序
- Author -
mdxy-dxy声明:登载此文出于传递更多信息之目的,并不意味着赞同其观点或证实其描述。
Reply on: @reply_date@
@reply_contents@