通过二维数组的某个字段进行分类,并重新组合:
<?php
namespace app\api\controller;
class Arraycz extends Base{
public function test(){
$data = [
[
"goods_cart_id" => 3299,
"goods_number" => 2,
"is_selected" => 0,
"wares_id" => 598,
"wares_name" => "番茄",
"desc_name" => "综合抗病性强,高产",
"new_price" => "220.00",
"stock" => 1973,
"brand_id" => 2,
"brand_name" => "植物大公司",
]
];
dump($data);
$res = $this->array_congzhu($data,'brand_id',['brand_id','brand_name']);
dump($res);
}
// 数组重组
//$array_data 二维数组
// $arr 要作为 根据 分类的数组id
// $arr_array要作为 根据 分类的数组
private function array_congzhu($array_data,$arr,$arr_array){
$data = array();
foreach($array_data as $k => $v){
$data[$v[$arr]][] = $v;
}
foreach($data as $k1 => $v1){
$res_data = [
'data' => $v1 //获取每组数据
];
foreach($arr_array as $k2 => $v2){
$new_array = [
$v2 => $v1[0][$v2] //拼接根据该 字段分类的 数组
];
$res_data = array_merge($new_array,$res_data); //数组合并
}
}
return $res_data;
}
}
|