需求:将两个数组根据iccid的值,合并为一个新数组
注意:因为测试的值使用postman输出的,请忽略数组格式,仅关注思路就好.
//数组1
>$res_have_card = array(2) {
[0] => array(3) {
["id"] => int(1024701)
["iccid"] => string(20) "123456B0000000049973"
["package_price_id"] => int(197)
}
[1] => array(3) {
["id"] => int(1024702)
["iccid"] => string(20) "123456B0000000049974"
["package_price_id"] => int(196)
}
}
//数组2
$requestMoney = array(2) {
[0] => array(2) {
["iccid"] => string(20) "123456B0000000049973"
["orderAmount"] => float(0)
}
[1] => array(2) {
["iccid"] => string(20) "123456B0000000049974"
["orderAmount"] => float(0)
}
}
方法一:嵌套循环遍历
//遍历$res_have_card 数组
foreach ($res_have_card as &$value) {
$year_num = NULL;
//遍历$requestMoney 数组
foreach ($requestMoney as $moneyVal) {
$money = 0;
$old_package_id = '';
//遍历两个数组,且其中iccid相等时,取出其中的值
if ($moneyVal['iccid'] == $value['iccid']) {
$money = $moneyVal['orderAmount'];
$old_package_id = $moneyVal['old_package_id'];
}
//构建订单详情表的数据,新数组
$order_detail_data[] = [
'h_id' => $value['h_id'],
'user_id' => $uid,
'start_time' => $now,
//通过比较iccid,将取出的值塞入新数组中
'old_package_id' => $old_package_id,
'new_package_id' => $new_package_id,
'number' => $year_num,
'charge_type' => 0,
'status' => 0,
'money' => $money,
'iccid' => $value['iccid'],
'order_detail_type' => 4
];
}
}
方法二:数组二的值变成键值对样式
//将$requestMoney 数组,拼接为新数组
foreach ($requestMoney as $v_data){
$iccid_money[$v_data['iccid']] = $v_data['orderAmount'];
}
//打印iccid_money出来的结果
array(2) {
["123456B0000000049973"] => float(0)
["123456B0000000049974"] => float(0)
}
//将$iccid_money数组,塞入$res_have_card
foreach ($res_have_card as &$v){
if (isset($iccid_money[$v['iccid']])){
$v['back_money'] = $iccid_money[$v['iccid']];
}else{
$v['back_money'] = 0;
}
}unset($v);
//打印res_have_card 出来的结果
array(2) {
[0] => array(4) {
["id"] => int(1024701)
["iccid"] => string(20) "123456B0000000049973"
["package_price_id"] => int(197)
["back_money"] => float(0)
}
[1] => array(4) {
["id"] => int(1024702)
["iccid"] => string(20) "123456B0000000049974"
["package_price_id"] => int(196)
["back_money"] => float(0)
}
}
最后
方法一逻辑简单,多了一个循环遍历,比较消耗内存
方法二比较简洁,节约内存,缺点是其中一个数组中的单数据对必须为2,否则无法拼接。
方法二,拼接数组结果的截图