MrGlass
MrGlass

Reputation: 9252

Joining 2 arrays in PHP

I am dealing with an API that only lets me access data by month. Occasionally, the data spans over 2 months, but there is no easy test to check against that.

I am already looping over the result data to find the data I need. I figure I can just call the API twice, for both months, and append 1 month onto the other.

I am trying to figure out how to join the 2 arrays together. Heres an example, I have:

firstMonth = array(0 => object0, 1 => object1, 2 => object2)
secondMonth = array(0 => object3, 1 => object4, 2 => object5)

and I need to join them so I have one array, like:

bothMonths = array(0 => object 0, 1 => object1, 2 => object2, 3 => object3, 4 => object4, 5 => object5)

So, how can I join my 2 arrays?

Upvotes: 0

Views: 96

Answers (4)

greg0ire
greg0ire

Reputation: 23255

You can use array_merge() to achieve this. Use + when you have different indexes.

Upvotes: 3

adlawson
adlawson

Reputation: 6431

array_merge();

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.

Upvotes: 2

abcde123483
abcde123483

Reputation: 3905

Try this:

function zip() {
    $args = func_get_args();
    $zipped = array();
    $n = count($args);
    for ($i=0; $i<$n; ++$i) {
        reset($args[$i]);
    }
    while ($n) {
        $tmp = array();
        for ($i=0; $i<$n; ++$i) {
            if (key($args[$i]) === null) {
                break 2;
            }
            $tmp[] = current($args[$i]);
            next($args[$i]);
        }
        $zipped[] = $tmp;
    }
    return $zipped;
}

$bothMonths = zip($firstMonth, $secondMonth);

print_r($bothMonths);

Similar to the ruby/python/haskell/... zip function, which is what you want

Upvotes: 0

knittl
knittl

Reputation: 265161

Use PHP's array_merge function:

 $bothMonths = array_merge($firstMonth, $secondMonth);

Upvotes: -2

Related Questions