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

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

问题描述:

I have two arrays one looks like this:

$shipping

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

and the other like this:

$totals

 [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 ) )

I want to merge the arrays together and using foreach display thier title and text values. However I dont want the array $shipping to be at the beginning or at the end, but to look like this:

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

anyway this can be done?

EDIT:

I would like my array to be displayed in this order:

 [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 )

This is what you want.

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

This will insert the shipping array, into the totals array at the third position, just like in your example of the solution.

Use array_merge()

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

assuming $shipping always has one item

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