How to group subarrays by a column value?

前端 未结 18 1965
一生所求
一生所求 2020-11-22 10:43

I have the following array

Array
(
    [0] => Array
        (
            [id] => 96
            [shipping_no] => 212755-1
            [part_no] =&         


        
18条回答
  •  孤独总比滥情好
    2020-11-22 11:27

    It's trivial to do with LINQ, which is implemented in PHP in several libraries, including YaLinqo*. It allows performing SQL-like queries on arrays and objects. The groubBy function is designed specifically for grouping, you just need to specify the field you want to group by:

    $grouped_array = from($array)->groupBy('$v["id"]')->toArray();
    

    Where '$v["id"]' is a shorthand for function ($v) { return $v["id"]; } which this library supports.

    The result will be exactly like in the accepted answer, just with less code.

    * developed by me

提交回复
热议问题