如何将两个关联数组合并为一个?

时间:2014-05-05 11:50:14

标签: php arrays

我有两个数组,如下所示:

   [0] => array(5) {
    ["part_id"] => string(2) "19"
    ["maker_id"] => string(2) "29"
    ["sale_deduction_type"] => string(1) "1"
    ["sale_deduction_value"] => string(2) "10"
    ["sale_name"] => string(8) "New Year"
  }

和新的:

[0] => (6) {
        ["bill_id"] => string(2) "31"
        ["part_number"] => string(18) "SN14CNANG56-M-BLUE"
        ["part_id"] => string(2) "19"
        ["part_quantity"] => string(1) "1"
        ["part_rate"] => string(6) "232.00"
        ["part_desc"] => string(12) "this is test"
      }

如何将这两个array1 [0]和array2 [0]组合成单个数组,如

array[0] => (10) {
        ["bill_id"] => string(2) "31"
        ["part_number"] => string(18) "SN14CNANG56-M-BLUE"
        ["part_id"] => string(2) "19"
        ["part_quantity"] => string(1) "1"
        ["part_rate"] => string(6) "232.00"
        ["part_desc"] => string(12) "this is test"
        ["maker_id"] => string(2) "29"
        ["sale_deduction_type"] => string(1) "1"
        ["sale_deduction_value"] => string(2) "10"
        ["sale_name"] => string(8) "New Year"
  }

使用array_merge或array_combine没有帮助。

2 个答案:

答案 0 :(得分:1)

将对象转换为数组并尝试,

$obj_merged = (object) array_merge((array) $array1[0], (array) $array2[0]);

正如@jack在上面评论的那样,

如果此数据来自JSON,请考虑将true作为第二个参数传递给json_decode()

答案 1 :(得分:0)

您正在尝试合并两个stdClass类型的对象而不是数组。如果预期输出应该是一个数组。 Convert them to arrays。然后使用array_merge。