«
php二维数组根据字段分组

时间:2021-12-22    作者:网络剑客    分类: php


$couponList =  [
  [
    "id" => 1
    "coupon_category_id" => 1
  ], [
    "id" => 2
    "coupon_category_id" => 3
  ],  [
    "id" => 3
    "coupon_category_id" => 5
  ]
]

调用方法 $couponGroup = arrayGroupBy($couponList, 'coupon_category_id');

处理方法

/**
 * @param array $data 二维数组
 * @param string $field 根据字段排序
 * @return mixed
 */
function arrayGroupBy(array $data, string $field)
{
    $result = [];
    foreach ($data as $k => $v) {
        $result[$v[$field]][] = $v;
    }

    return $result;
}

标签: php