0

I have two arrays:

$array1 = array(299945 => [13654 => [9917 => [0 => '0', 9 => '9', 33 => '33']]]);
$array2 = array(13654 => [9940 => [0 => '0']]);

Each of these are created from different DBQueries which create these results.

I know want to take the '9940' key from $array2 and push it into $array1 so that it will be another element in the 13654 array. Thus the final result would be:

$array1 = array(299945 =>[13654 => [9917 => [0 => '0', 9 => '9', 33 => '33'], 9940 => [0 => '0']]])

How can I do this?

1
  • Is the key you are looking for in first array always located on second level (depth)? Or do you want to search for the key 9940 recursively in the array? So the key may also be located in other sub arrays much deeper in your first array. Commented Jan 18, 2018 at 8:56

2 Answers 2

1

There's a few ways of doing this, here's one that uses array_replace_recursive():

<?php

header('Content-type: text/plain');

$array1 = array(299945 => [13654 => [9917 => [0 => '0', 9 => '9', 33 => '33']]]);
$array2 = array(13654 => [9940 => [0 => '0']]);

$array3 = array_replace_recursive($array1, [key($array1) => $array2]);

print_r($array3);

Output:

Array
(
    [299945] => Array
        (
            [13654] => Array
                (
                    [9917] => Array
                        (
                            [0] => 0
                            [9] => 9
                            [33] => 33
                        )

                    [9940] => Array
                        (
                            [0] => 0
                        )

                )

        )

)
Sign up to request clarification or add additional context in comments.

8 Comments

Although this solution correctly uses array_merge_recursive, it will not work if you change keys, even with exactly such an array structure
@splash58 change which keys?
The initial key 299945. Without the OP stipulating the schema of the given arrays, this is the best answer I can give.
@e_i_pi Are you shure? :) Use [key($array1) => $array2], at least
I think that we will see new question for that in some time, or OP will ask you again here, because structure of array1 as [12=>[13=>], [14=>]] seems to be very possible
|
0

If you just want a union of two arrays, there is not much to it:

$array1 += $array2

You should probably think about more complex situation with duplicate keys and issues like that, so I usually find array_merge to be the better tool for adding two arrays together.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.