PHP 根據key 給二維數組分組_php執行個體

來源:互聯網
上載者:User

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

先來看以下數組,

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 keyif (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 給二維數組分組,希望對大家有所協助,如果大家有任何疑問請給我留言,小編會及時回複大家的。在此也非常感謝大家對雲棲社區網站的支援!

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.