在特定顺序PHP中合并两个数组

时间:2014-04-10 20:05:50

标签: php arrays

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

$航运

Array ( [0] => Array ( 
         [code] => sub_total 
         [title] => Sub-Total 
         [text] => $1,728.00 
         [value] => 1728 
         [sort_order] => 1 )

和另一个像这样:

$总计

 [0] => Array ( 
        [code] => tax 
        [title] => Georgia Sales Tax 
        [text] => $120.96 
        [value] => 120.96 
        [sort_order] => 5 ) 
 [1] => Array (    
        [code] => total 
        [title] => Total 
        [text] => $1,848.96 
        [value] => 1848.96 
        [sort_order] => 9 ) 
 [2] => Array ( 
        [code] => free.free 
        [title] => Free Shipping 
        [cost] => 0 
        [tax_class_id] => 0 
        [text] => $0.00 ) )

我想将数组合并在一起并使用foreach显示其titletext值。但是我不希望数组$shipping位于开头或结尾,但看起来像这样:

   Sub-Total                $1,728.00
   Free Shipping            $0.00
   Georgia Sales Tax        $120.96
   Total                    $1,848.96

无论如何这可以做到吗?

编辑:

我希望我的数组按此顺序显示:

 [0] => Array ( 
        [code] => tax 
        [title] => Georgia Sales Tax 
        [text] => $120.96 
        [value] => 120.96 
        [sort_order] => 5 )  
 [1] => Array (          // <--- this is where I want the $shipping array
        [code] => free.free 
        [title] => Free Shipping 
        [cost] => 0 
        [tax_class_id] => 0 
        [text] => $0.00 ) )
 [2] => Array (      
         [code] => sub_total 
         [title] => Sub-Total 
         [text] => $1,728.00 
         [value] => 1728 
         [sort_order] => 1 )
 [3] => Array ( 
        [code] => total 
        [title] => Total 
        [text] => $1,848.96 
        [value] => 1848.96 
        [sort_order] => 9 )

3 个答案:

答案 0 :(得分:2)

这就是你想要的。

array_splice($totals, 2, 0, $shipping);

这会将装运数组插入第三个位置的总计数组中,就像在解决方案示例中一样。

答案 1 :(得分:1)

使用array_merge()

$newArray = array_merge($totals, $shipping);

答案 2 :(得分:0)

假设$ shipping始终有一个项目

$newArray = array_push($totals, $shipping[0])