I don't want to use array_merge() as it results in i misunderstood that all values with the same keys would be overwritten. i have two arrays
$array1 = array(0=>'foo', 1=>'bar');
$array2 = array(0=>'bar', 1=>'foo');
and would like to combin开发者_如何学Goe them resulting like this
array(0=>'foo', 1=>'bar',2=>'bar', 3=>'foo');
array_merge()
appends the values of the second array to the first. It does not overwrite keys.
Your example, results in:
Array ( [0] => foo [1] => bar [2] => bar [3] => foo )
However, 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.
Unless this was just an example to another problem you were having?
Does this answer your question? I'm not sure exactly what you're trying to accomplish, but from your description it sounds like this will work:
$array1 = array(0=>'foo', 1=>'bar');
$array2 = array(0=>'bar', 1=>'foo');
foreach ($array2 as $i) {
$array1[] = $i;
}
echo var_dump($array1);
There are probably much better ways but what about:
$newarray= array();
$array1 = array(0=>'foo', 1=>'bar');
$array2 = array(0=>'bar', 1=>'foo');
$dataarrays = array($array1, $array2);
foreach($dataarrays as $dataarray) {
foreach($dataarray as $data) {
$newarray[] = $data;
}
}
print_r($newarray);
$result = array_keys(array_merge(array_flip($array1), array_flip($array2)));
var_dump($result);
If someone stumbles upon this, this is a way to do it nowadays:
var_dump(array_merge_recursive($array1, $array2));
精彩评论