一般这种情况是为了前端更方便的进行数据展示才进行数组的重组
原始的数据
// $old_data
array(3) {
[0] => array(18) {
["building_name"] => string(10) "蓝宝A栋"
["store_name"] => string(6) "蓝宝"
["store_id"] => int(7)
["building_id"] => int(13)
["is_landlord"] => int(1)
}
[1] => array(18) {
["building_name"] => string(12) "蓝宝分散"
["store_name"] => string(6) "蓝宝"
["store_id"] => int(7)
["building_id"] => int(134)
["is_landlord"] => int(2)
}
[2] => array(18) {
["building_name"] => string(10) "南非A栋"
["store_name"] => string(6) "南非"
["store_id"] => int(26)
["building_id"] => int(135)
["is_landlord"] => int(1)
}
}
想要的效果
array(2) {
[7] => array(2) {
[0] => array(18) {
["building_name"] => string(10) "蓝宝A栋"
["store_name"] => string(6) "蓝宝"
["store_id"] => int(7)
["building_id"] => int(13)
["is_landlord"] => int(1)
}
[1] => array(18) {
["building_name"] => string(12) "蓝宝分散"
["store_name"] => string(6) "蓝宝"
["store_id"] => int(7)
["building_id"] => int(134)
["is_landlord"] => int(2)
}
}
[26] => array(1) {
[0] => array(18) {
["building_name"] => string(10) "南非A栋"
["store_name"] => string(6) "南非"
["store_id"] => int(26)
["building_id"] => int(135)
["is_landlord"] => int(1)
}
}
}
封装函数
/**
* @name: 根据相同值重组数组
* @param {*} $array 数组数据
* @param {*} $value_name 字段名
* @author: Turbo
* @Date: 2021-06-21 10:03:05
*/
public function array_val_chunk($array, $value_name)
{
$result = [];
$ar2 = []; // 临时存放
foreach ($array as $key => $value) {
foreach ($array as $k => $val) {
// 将相同的值存放到一个临时数组
if($value[$value_name] == $val[$value_name]){
$ar2[] = $val;
}
}
// 丢进以相同值为键值的数组
$result[$value[$value_name]] = $ar2;
$ar2 = [];
}
return $result;
}
调用函数
$value_name = 'store_id';
$new_data = $this->array_val_chunk($old_data, $value_name);
一切源于热爱 ~