咱們常常拿到一個二維數組出來,會發現結果和本身想要的有些誤差,可能須要根據二維數組裏的某個字段對數組分組。
先來看如下數組,
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 ) )
這裏是一個很典型的例子,若是我但願把 數組中的數據 根據 type(分組) 分開處理,若是不分組,可能循環上會很是冗餘,因此有了下面的一個分組函數:php
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 : 二維數組數組
$key: 須要分組的key函數
獲得的結果是:ui
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 ) ) )