首頁  >  文章  >  後端開發  >  PHP 根據key 將二維數組分組

PHP 根據key 將二維數組分組

巴扎黑
巴扎黑原創
2016-12-22 14:22:461507瀏覽

我們常常拿到一個二維數組出來,會發現結果和自己想要的有些偏差,可能需要根據二維數組裡的某個字段對數組分組。

先來看以下數組,

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
)
)
)


陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn