1
\$\begingroup\$

In such an array:

$arr = Array (
    [key0] => Array (
        [subkey0] => Array (
            [0] => "value0"
            [1] => "value1"
        )
        [subkey1] => Array (
            [0] => "value0"
            [1] => "value1"
        )
    )
    [key1] => Array (
        [subkey0] => Array (
            [0] => "value0"
            [1] => "value1"
        )
        [subkey1] => Array (
            [0] => "value0"
            [1] => "value1"
        )
    )
)

In order to add $varX to the end of $arr[keyX][subkeyX] as [X] => $varX, I use, inside a loop, the following:

$arr[$key] = array(
    "subkey0" => array_merge((array)$arr[$key]["subkey0"], (array)$var1),
    "subkey1" => array_merge((array)$arr[$key]["subkey1"], (array)$var2)
    ...
)

And I might be working with even more nested arrays, so I was wondering if there was a way for subkey0 to refer to itself, or if I could do something like:

"subkeyX" =>+ (array)$varX

Or use array_merge() in a different way to add $varX to the end of subkeyX as [X] => $varX.

\$\endgroup\$

1 Answer 1

3
\$\begingroup\$

I don't know if I understand the question right. But this should work.

foreach ($keys as $key) {
    $arr2[$key]['subkey0'][] = $var1;
    $arr2[$key]['subkey1'][] = $var2;
}
\$\endgroup\$
2
  • \$\begingroup\$ Thanks but it does not seem to work. For instance, check this phpfiddle -- click on run to see the results. \$\endgroup\$
    – Alex
    Mar 30, 2013 at 1:11
  • \$\begingroup\$ Sorry, my answer was not clear enough. I edited it. \$\endgroup\$ Mar 30, 2013 at 1:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.