简体   繁体   中英

php assoc array

I have two assoc array i want to creat one array out of that
Eg

a(a=>1
  b=>3
  f=>5 
 )
b(a=>4
  e=>7
  f=>9 
 )

output must be

c(
   a=>1
   b=>3
   f=>5 
   a=>4
   e=>7
   f=>9 
)

i am new in php

Use array_merge() . Your resulting array CAN NOT have more than one entry for the same key, so the second a => something will overwrite the first.

Use the + operator to return the union of two arrays.

The new array is constructed from the left argument first, so $a + $b takes the elements of $a and then merges the elements of $b with them without overwriting duplicated keys. If the keys are numeric, then the second array is just appended.

This ey difference of the + operator and the function, array_merge is that array merge overwrites duplicated keys if the latter arguments contain that key. The documentation puts it better:

If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.

If the keys are different, then use array_merge()

<?php
    $a1=array("a"=>"Horse","b"=>"Cat");
    $a2=array("c"=>"Cow");
    print_r(array_merge($a1,$a2));
?>

OUTPUT:

Array ( [a] => Horse [b] => Cat [c] => Cow )

If the keys are the same, then use array_merge_recursive()

<?php
    $ar1 = array("color" => array("favorite" => "red"), 5);
    $ar2 = array(10, "color" => array("favorite" => "green", "blue"));
    $result = array_merge_recursive($ar1, $ar2);
    print_r($result);
?>

OUTPUT:

Array
(
    [color] => Array
        (
            [favorite] => Array
                (
                    [0] => red
                    [1] => green
                )

            [0] => blue
        )

    [0] => 5
    [1] => 10
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM