将1个数组的值合并到键相同的另一个数组

时间:2018-07-12 21:22:35

标签: php laravel

我有2个数组,我想将一个数组中的键值彼此相等的值从一个数组推到另一个数组。

第一个数组

    $retail_rates=[
    {
        "supplier": "ALAMO",
        "rateTotalAmount": 293.44,
        "estimatedTotalAmount": 495.34, //i want to add this AS retailTotalAmount
        "numDays": 9 // i want to add this
    },
    {
        "supplier": "HERTZ",
        "rateTotalAmount": 317.16,
        "estimatedTotalAmount": 537.43,
        "numDays": 9
    }
]

第二个数组

    $net_rates =[
    {
        "reference_number": "COMPEKYP7537400-2401",
        "supplier": "HERTZ",
        "rateTotalAmount": 203.01,
        "estimatedTotalAmount": 291.21
    },
    {
        "reference_number": "REF_ID:867692955",
        "supplier": "ALAMO",
        "rateTotalAmount": 147,
        "estimatedTotalAmount": 225.58
    }
]

我要结束的事情

    $final_array=[
    {
        "reference_number": "COMPEKYP7537400-2401",
        "supplier": "HERTZ",
        "rateTotalAmount": 203.01,
        "estimatedTotalAmount": 291.21,
        "retailTotalAmount": 537.43,
         "numDays": 9
    },
    {
        "reference_number": "REF_ID:867692955",
        "supplier": "ALAMO",
        "rateTotalAmount": 147,
        "estimatedTotalAmount": 225.58,
        "retailTotalAmount": 495.34
         "numDays": 9
    }
         // and so on all the way through

]

我尝试了几次循环,但似乎无法正确填充它。请帮忙

2 个答案:

答案 0 :(得分:3)

在第一个数组上迭代一次,并创建一个以供应商为键的assoc数组。然后遍历第二个数组,并将其附加到第一个数组。

$final_array = [];
foreach ($retail_array as $item) {
    $final_array[$item['supplier']] = $item;
}

foreach ($net_array as $item) {
    if (isset($final_array[$item['supplier']])) {
        $final_array[$item['supplier']] = $item + $final_array[$item['supplier']];
    } else {
        $final_array[$item['supplier']] = $item;
    }
}

答案 1 :(得分:2)

尝试一下

$result = [];
foreach ($net_rates as $net_key => $net_rate) {
    foreach ($retail_rates as $retail_key => $retail_rate) {

        if ($retail_rate['supplier'] != $net_rate['supplier']) {
            continue;
        }

        $data = $net_rate;
        $data['retailTotalAmount'] = $retail_rate['estimatedTotalAmount'];
        $data['numDays'] = $retail_rate['numDays'];
        $result[] = $data;

        unset($retail_rates[$retail_key]);
        unset($net_rates[$net_key]);
        break;
    }
}
$result = array_merge($result, $retail_rates);
$result = array_merge($result, $net_rates);
dd($result);

结果是

array:2 [▼
  1 => array:6 [▼
    "reference_number" => "COMPEKYP7537400-2401"
    "supplier" => "HERTZ"
    "rateTotalAmount" => 203.01
    "estimatedTotalAmount" => 291.21
    "retailTotalAmount" => 537.43
    "numDays" => 9
  ]
  0 => array:6 [▼
    "reference_number" => "REF_ID:867692955"
    "supplier" => "ALAMO"
    "rateTotalAmount" => 147
    "estimatedTotalAmount" => 225.58
    "retailTotalAmount" => 495.34
    "numDays" => 9
  ]
]