Page 1 of 1

array_merge?

Posted: Wed Aug 04, 2004 5:20 am
by tores
Hi

I have to arrays, a and b. Array a have the following keys: 0,2 and 4.
Array b have keys 1, 3 and 5.
What I want to do is reset the keys in a so they equal 0, 1 and 2, and in b to 3, 4 and 5.
Finally the two arrays should be merged into one with keys 0, 1, 2, 3, 4 and 5.

Can this be done in a simple way?

Posted: Wed Aug 04, 2004 5:23 am
by feyd

Code: Select all

asort($newarray = array_merge($a,$b));
[edit: oops]


err.. sorry..

Code: Select all

ksort($newarray = array_merge($a,$b))

Posted: Wed Aug 04, 2004 5:37 am
by tores
asort($newarray = array_merge($a,$b));
Will not work as i described. The keys for a and b is not reset.
newarray will be inn the order ababab instead of aaabbb.

Posted: Wed Aug 04, 2004 5:39 am
by tores
ksort() should do it... Thanks

[edit] or not... The order is still ababab.

Something like this should work... Haven't tested it yet.

Code: Select all

<?php
    $key = 0;

    while($tmp = each($a))
      $newa[$key++] = $tmp['value'];

    while($tmp = each($b))
      $newb[$key++] = $tmp['value'];

    $newarray = array_merge($newa, $newb);

?>

Posted: Wed Aug 04, 2004 11:25 am
by JAM
Did I misunderstand this? If so, I appologize... If not:

Code: Select all

$a = array (
    0 => 'foo', 2 => 'bar', 4 => 'moo'
);
$b = array (
    1 => 'c', 3 => 'a', 5 => 'b'
);
$new_arr= array_merge_recursive($a, $b);
print_r($new_arr);
Result:

Code: Select all

Array
(
    &#1111;0] =&gt; foo
    &#1111;1] =&gt; bar
    &#1111;2] =&gt; moo
    &#1111;3] =&gt; c
    &#1111;4] =&gt; a
    &#1111;5] =&gt; b
)