Skip to content
Advertisement

Pair key values that in same array – PHP

This is my JSON data:

{
    "1": "apple",
    "2": "banana",
    "3": "orange"
     ...
}

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

["apple","banana"] // [1,2]
["banana","orange"] // [2,3]
...

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

$k = 1;
for($i = 1; $i < count($jsonData); ++$i) {
            $pair = [$jsonData[$i], $jsonData[$k + 1]];
            $pairs += $pair;
            $k++;
        }

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:

$pairs = [];
for($i = 1; $i < count($jsonData); ++$i) {
    $pair = [$jsonData[$i], $jsonData[$i + 1]];
    $pairs[] = $pair;
}
print_r($pairs);

Fiddle here.

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