Yang
Yang

Reputation: 8701

Array values always get overriden by the last key inside foreach

There's a following array:

$input = [
    'adults' => [1, 2],
    'children' => [3, 4]
];

The number of keys and values might be dynamic in this array (but the structure, key => Numeric:Array always remains the same).

I want to turn this array into the following structure:

[
   [
      'adults' => 1,
      'children' => 3
   ],

   [
      'adults' => 2,
      'children' => 4
   ]
]

In order to achieve this, I wrote the following function:

function parse(array $input)
{
    $output = [];

    $keys = array_keys($input);

    foreach ($input as $parameter => $values) {
        $internal = [];

        foreach ($values as $value) {
            foreach ($keys as $key) {
                if (!isset($internal[$key])) {
                    $internal[$key] = $value;
                }
            }
        }

        $output[] = $internal;
    }

    return $output;
}

But this gives an unxpected output:

print_r(parse($input));

Array
(
    [0] => Array
        (
            [adults] => 1
            [children] => 1
        )

    [1] => Array
        (
            [adults] => 3
            [children] => 3
        )

)

Somehow the values always get overriden by the last one inside the parsing function. So what might cause this error?

Upvotes: 1

Views: 59

Answers (1)

rjdown
rjdown

Reputation: 9227

If I understand the logic correctly, this should work:

function parse(array $input)
{
    $output = [];
    foreach ($input as $key1 => $values) {
        foreach ($values as $key2 => $value) {
            $output[$key2][$key1] = $value;
        }
    }
    return $output;
}

https://3v4l.org/HeXUp

With a larger array

$input = [
    'adults' => [1, 2],
    'children' => [3, 4],
    'foo' => [2, 7],
    'bar' => [4, 6],
];

This returns

Array
(
    [0] => Array
        (
            [adults] => 1
            [children] => 3
            [foo] => 2
            [bar] => 4
        )

    [1] => Array
        (
            [adults] => 2
            [children] => 4
            [foo] => 7
            [bar] => 6
        )

)

Upvotes: 1

Related Questions