怎么在PHP中根據(jù)key對(duì)二維數(shù)組進(jìn)行分組?針對(duì)這個(gè)問題,這篇文章詳細(xì)介紹了相對(duì)應(yīng)的分析和解答,希望可以幫助更多想解決這個(gè)問題的小伙伴找到更簡單易行的方法。
創(chuàng)新互聯(lián)公司服務(wù)項(xiàng)目包括思禮網(wǎng)站建設(shè)、思禮網(wǎng)站制作、思禮網(wǎng)頁制作以及思禮網(wǎng)絡(luò)營銷策劃等。多年來,我們專注于互聯(lián)網(wǎng)行業(yè),利用自身積累的技術(shù)優(yōu)勢、行業(yè)經(jīng)驗(yàn)、深度合作伙伴關(guān)系等,向廣大中小型企業(yè)、政府機(jī)構(gòu)等提供互聯(lián)網(wǎng)行業(yè)的解決方案,思禮網(wǎng)站推廣取得了明顯的社會(huì)效益與經(jīng)濟(jì)效益。目前,我們服務(wù)的客戶以成都為中心已經(jīng)輻射到思禮省份的部分城市,未來相信會(huì)繼續(xù)擴(kuò)大服務(wù)區(qū)域并繼續(xù)獲得客戶的支持與信任!先來看以下數(shù)組,
Array ( [0] => Array ( [id] => 1 [wo_id] => 2 [evaluate_id] => 1 [type] => 分組1 [ctime] => 2016-12-02 11:39:34 ) [1] => Array ( [id] => 2 [wo_id] => 31 [evaluate_id] => 2 [type] => 分組1 [ctime] => 2016-12-12 11:39:50 ) [2] => Array ( [id] => 3 [wo_id] => 31 [evaluate_id] => 4 [type] => 分組2 [ctime] => 2016-12-02 11:40:01 ) [3] => Array ( [id] => 4 [wo_id] => 2 [evaluate_id] => 5 [type] => 分組2 [ctime] => 2016-12-07 10:21:40 ) [4] => Array ( [id] => 5 [wo_id] => 2 [evaluate_id] => 3 [type] => 分組2 [ctime] => 2016-12-07 10:21:51 ) [5] => Array ( [id] => 6 [wo_id] => 2 [evaluate_id] => 2 [type] => 分組3 [ctime] => 2016-12-07 10:21:56 ) [6] => Array ( [id] => 7 [wo_id] => 4 [evaluate_id] => 2 [type] => 分組3 [ctime] => 2016-12-07 10:22:10 ) )
這里是一個(gè)很典型的例子,如果我希望把 數(shù)組中的數(shù)據(jù) 根據(jù) type(分組) 分開處理,如果不分組,可能循環(huán)上會(huì)非常冗余,所以有了下面的一個(gè)分組函數(shù):
public static function array_group_by($arr, $key) { $grouped = []; foreach ($arr as $value) { $grouped[$value[$key]][] = $value; } // Recursively build a nested grouping if more parameters are supplied // Each grouped array value is grouped according to the next sequential key if (func_num_args() > 2) { $args = func_get_args(); foreach ($grouped as $key => $value) { $parms = array_merge([$value], array_slice($args, 2, func_num_args())); $grouped[$key] = call_user_func_array('array_group_by', $parms); } } return $grouped; }
$arr : 二維數(shù)組
$key: 需要分組的key
得到的結(jié)果是:
Array ( [分組2] => Array ( [0] => Array ( [id] => 1 [wo_id] => 2 [evaluate_id] => 1 [ctime] => 2016-12-02 11:39:34 [type] => 分組2 ) [1] => Array ( [id] => 2 [wo_id] => 31 [evaluate_id] => 2 [ctime] => 2016-12-12 11:39:50 [type] => 分組2 ) [2] => Array ( [id] => 3 [wo_id] => 31 [evaluate_id] => 4 [ctime] => 2016-12-02 11:40:01 [type] => 分組2 ) ) [分組1] => Array ( [0] => Array ( [id] => 4 [wo_id] => 2 [evaluate_id] => 5 [ctime] => 2016-12-07 10:21:40 [type] => 分組1 ) [1] => Array ( [id] => 5 [wo_id] => 2 [evaluate_id] => 3 [ctime] => 2016-12-07 10:21:51 [type] => 分組1 ) ) )
關(guān)于怎么在PHP中根據(jù)key對(duì)二維數(shù)組進(jìn)行分組問題的解答就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道了解更多相關(guān)知識(shí)。