array_merge?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
tores
Forum Contributor
Posts: 120
Joined: Fri Jun 18, 2004 3:04 am

array_merge?

Post 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?
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

Code: Select all

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


err.. sorry..

Code: Select all

ksort($newarray = array_merge($a,$b))
tores
Forum Contributor
Posts: 120
Joined: Fri Jun 18, 2004 3:04 am

Post 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.
tores
Forum Contributor
Posts: 120
Joined: Fri Jun 18, 2004 3:04 am

Post 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);

?>
User avatar
JAM
DevNet Resident
Posts: 2101
Joined: Fri Aug 08, 2003 6:53 pm
Location: Sweden
Contact:

Post 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
)
Post Reply