我們經常拿到一個二維數組出來,會發現結果和自己想要的有些偏差,可能需要根據二維數組裡的某個字段對數組分組。
先來看以下數組,
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(分組) 分開處理,如果不分組,可能循環上會非常冗余,所以有了下面的一個分組函數:
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
得到的結果是:
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 ) ) )
以上所述是小編給大家介紹的PHP 根據key 給二維數組分組,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對網站的支持!