PHP Merge values with same key

Ask about a PHP problem here.
Post Reply
User avatar
EcazS
Posts: 789
Joined: Fri May 06, 2011 5:29 pm

PHP Merge values with same key

Post by EcazS »

I was working on........something and I thought I'd tidy up the output a little bit.....*cough*

Anyways, I have two arrays like this,
Array (
     [0] => Zero
     [1] => One
)
Array (
     [0] => 0
     [1] => 1
)
But now, I want to output it like,
Array(
     [0] => Array(
          [0] => "Zero"
          [1] => 0
     )
     [1] => Array(
          [0] => "One"
          [1] => 1
     )
)
But I have no idea how I would merge the values with the same key, if that makes sense. I looked into array_merge which doesn't work. I also looked into array_merge_recursively which didn't seem to do anything different.

So, any help on this?
User avatar
jacek
Site Admin
Posts: 3262
Joined: Thu May 05, 2011 1:45 pm
Location: UK
Contact:

Re: PHP Merge values with same key

Post by jacek »

I cant think of a way other than using a for loop. There probably is a function that does this.

As an example
for ($i = 0; $i < $total; ++$i){
    $new_array[$i] = array($top_array[$i], $bottom_array[$i]);
}
would do that.

There is most likely a better way though !
Image
User avatar
EcazS
Posts: 789
Joined: Fri May 06, 2011 5:29 pm

Re: PHP Merge values with same key

Post by EcazS »

Hmm, I'll have to try it out. But that would mean that I'd have three loops for each request. Which looks rather odd.

Also, why is this in General Chat? :shock: :?
User avatar
jacek
Site Admin
Posts: 3262
Joined: Thu May 05, 2011 1:45 pm
Location: UK
Contact:

Re: PHP Merge values with same key

Post by jacek »

EcazS wrote:Also, why is this in General Chat? :shock: :?
You put is here !
Image
Post Reply