如何将关联数组与相同的键组合在一起

时间:2013-12-28 10:18:19

标签: php

我正在尝试将这两个数组合并:

Array ( [carrier] => USPS Ground [rate] => 6.00 ) 
Array ( [carrier] => FedEx Ground [rate] => 11.01 ) 

当我使用array_merge时,我得到:

Array ( [carrier] => FedEx Ground [rate] => 11.01 ) 

因为键是相同的。

使用array_combine时,你得到:

Array ( [0] => Array ( [USPS Ground] => FedEx Ground [6.00] => 11.01 ) )

使用array_merge_recursive时,我得到:

Array ( [0] => Array ( [carrier] => Array ( [0] => USPS Ground [1] => FedEx Ground ) [rate] => Array ( [0] => 6.00 [1] => 11.01 ) ) )

我试图将此作为我的结果:

Array ( [0] => Array ( [carrier] => USPS Ground [rate] => 6 ) [1] => Array ( [carrier] => FedEx Ground [rate] => 11.01 ) )

1 个答案:

答案 0 :(得分:3)

为什么不使用array_push

array_push($yournewarray,$array1,$array2);  

示例...

<?php
$arr1=Array ( 'carrier' => 'USPS Ground', 'rate' => 6.00 );
$arr2=Array ( 'carrier' => 'FedEx Ground', 'rate' => 11.01 );
$new_array=array();
array_push($new_array,$arr1,$arr2); //You can any number of arrays here, not just two
print_r($new_array);

输出:

Array
(
    [0] => Array
        (
            [carrier] => USPS Ground
            [rate] => 6
        )

    [1] => Array
        (
            [carrier] => FedEx Ground
            [rate] => 11.01
        )

)