Tell me more ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

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.

share|improve this question

1 Answer

up vote 3 down vote accepted

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;
}
share|improve this answer
Thanks but it does not seem to work. For instance, check this phpfiddle -- click on run to see the results. – Alex Mar 30 at 1:11
Sorry, my answer was not clear enough. I edited it. – AlucardTheRipper Mar 30 at 1:54
Of course, my mistake. Thanks – Alex Mar 30 at 2:18
+1 great clarity – Rob Apodaca Mar 31 at 16:40

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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