Skip to content
Advertisement

Pair key values that in same array – PHP

This is my JSON data:

JavaScript

I am trying to loop through and pair the values in the following way:

JavaScript

So far I have tried this. It loops thru 2 times and only gives me [1,2] pair result.

JavaScript

Result: ["apple","banana"]

Note that array can be any size but cannot less or equal to 1. How could I accomplish this in PHP?

Thank you!

Advertisement

Answer

Replace $pairs += $pair; with $pairs[] = $pair;.

Because + for arrays just skips keys that are already in array. And these keys are 0 and 1 which appear after the first iteration of your for loop.

As @Nick stated – $k is redundant. So your code can be:

JavaScript

Fiddle here.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement