相关联的两条数据合并成一条用循环怎么解决
假设list是查询的结果几条相关联数据是根据order_sn是否相同,如相同则可合并(即将相同的列内的需要合并的数据取出放入一个新数组中manual_verify_detail),拼入任一相同order_sn的列,最终newData为需要的结果
方法一:相同key下标法
只要后续有找到相同下标的列,就进行数据处理,把数据丢到相同该相同key的数组里
$data = [];
foreach ($list as $v) {
$orderSn = $v['order_sn'] ?? '';
if (empty($data[$orderSn])) {
$data[$orderSn] = $v;
}
$data[$orderSn]['mobile'] = Tools::mobileHide($v['mobile'], $isHide);
$manualVerifyDetail = [
'user_type' => $v['user_type'],
'user_type_content' => $v['user_type_content'],
'name' => $v['name'],
'status' => $v['status'],
'conclusion' => $v['conclusion'],
'id' => $v['id'],
];
$data[$orderSn]['manual_verify_detail'][] = $manualVerifyDetail;
}
$newData = array_values($data);
方法:双重循环对比法
如果第二重循环的有相同key的进行数据处理
$data = [];
foreach ($list as $v) {
$orderSn = $v['order_sn'];
$data[$orderSn] = $v;
$data[$orderSn]['mobile'] = Tools::mobileHide($v['mobile'], $isHide);
foreach ($list as $v2) {
if ($v['order_sn'] == $v2['order_sn']) {
$data[$orderSn]['manual_verify_detail'][] = [
'userType' => $v2['user_type'],
'userTypeContent' => $v2['user_type_content'],
'name' => $v2['name'],
'status' => $v2['status'],
'conclusion' => $v2['conclusion'],
];
}
}
}
$newData = array_values($data);