合并两个数组相同索引的键值

时间:2018-03-23 12:35:19

标签: php merge associative-array

我有2个数组,我必须在同一个索引中合并数组。

Array
(
    [0] => Array
        (
            [vendor_name] => MIRAGE PET PRODUCTS
            [count_es] => 86
            [outofstalk] => 19
            [listing] => 64
            [pricing] => 2
            [discontinued] => 1
            [others] => 0
        )

    [1] => Array
        (
            [vendor_name] => THE HOME DEPOT
            [count_es] => 1
            [outofstalk] => 0
            [listing] => 1
            [pricing] => 0
            [discontinued] => 0
            [others] => 0
        )

)

这是第一个数组和

Array
   (   [0] => Array
        (
            [incorrect_esc_count] => 1
        )

    [1] => Array
        (
            [incorrect_esc_count] => 0
        ) 

) 

这是第二个数组。

我想要那个结果

Array
(
    [0] => Array
        (
            [vendor_name] => MIRAGE PET PRODUCTS
            [count_es] => 86
            [outofstalk] => 19
            [listing] => 64
            [pricing] => 2
            [discontinued] => 1
            [others] => 0
            [incorrect_esc_count] => 1
        )

    [1] => Array
        (
            [vendor_name] => THE HOME DEPOT
            [count_es] => 1
            [outofstalk] => 0
            [listing] => 1
            [pricing] => 0
            [discontinued] => 0
            [others] => 0
            [incorrect_esc_count] => 0
        )
)

我怎样才能实现这一目标? `第一个数组来自一个变量,第二个数组来自另一个变量。我希望这个sholud在一个数组中,因为对于视图我使用angular.js并使用表

1 个答案:

答案 0 :(得分:0)

您正在尝试将两个多维关联数组合并为一个。这段代码应该适用于您,并提供一些注释:

<?php
// declare the first array, I did not add all of the key-value pairs
$marr1 = array
  (
  array("vendor_name"=>"MIRAGE PET PRODUCTS","count_es"=>86,"outofstalk"=>19),
  array("vendor_name"=>"THE HOME DEPOT","count_es"=>1,"outofstalk"=>0)
  );
// declare second array
$marr2 = array
  (
  array("incorrect_esc_count"=>1),
  array("incorrect_esc_count"=>0)
  );
// declare third empty array to hold the result
$marr3 = array();
// loop through both arrays
// this will not work if your arrays have different lengths
for ($i = 0; $i < count($marr1); $i++) {
    // merge the ith elements of both array and then push that array into the third array
    array_push($marr3, array_merge($marr1[$i],$marr2[$i]));
}
// print out result
print_r($marr3);
?>