0

I have two arrays both guaranteed to be the same length. The two arrays are of the following structures

array1

Array
(
    [0] => Array
        (
            [id] => 841052
            [store] => 11
            [position] => 1
        )

    [1] => Array
        (
            [id] => 1613197
            [store] => 11
            [position] => 401
        )

    [2] => Array
        (
            [id] => 1648966
            [store] => 11
            [position] => 1
        )

    [3] => Array
        (
            [id] => 1656857
            [store] => 11
            [position] => 1
        )
....
....
)

array2

Array

(
    [0] => 5/20/2019
    [1] => 7/7/2019
    [2] => 12/16/2018
    ...
    ...
)

How do I append every value of array2 as a key value pair to array1 to get the following array. The key name can be whatever I just chose date.

Array
(
    [0] => Array
        (
            [id] => 841052
            [store] => 11
            [position] => 1
            [date] => 5/20/2019
        )

    [1] => Array
        (
            [id] => 1613197
            [store] => 11
            [position] => 401
            [date] => 7/7/2019
        )

    [2] => Array
        (
            [id] => 1648966
            [store] => 11
            [position] => 1
            [date] => 12/16/2018
        )
)
...
...
...

I have tried

array_push($array1, $array2);

It just pushed it to the last element of the array. I thought of using two foreach loops but couldn't get ti to work. Is there a built in php function that will do this, or do I have to do it in loops.

2 Answers 2

3

Just walk $array1 and modify each sub-array by adding the new key and the value of $array2 with the same key:

array_walk($array1, function(&$v, $k) use($array2) { $v['date'] = $array2[$k]; });
Sign up to request clarification or add additional context in comments.

4 Comments

getting a array_map() expects parameter 1 to be a valid callback, array must have exactly two members error. Using PHP 5.3.3 if that matters
Damn, I started with map but it should be array_walk.
@AbraCadaver This answer is better than mine. Only doubt, if it does not correspond the number of elements could give error.
@ees3 This is better for you!
2

try this:

    $array1 = array(array("id" => 841052, "store" => "11", "position" => "1"), array("id" => 1613197, "store" => "11", "position" => "401"),);
    $array2 = array("5/20/2019", "7/7/2019");
    foreach ($array1 as $index => $valuearray1) {
        if (array_key_exists($index, $array2)) {
            $array1[$index]["date"] = $array2[$index];
        }
    }
    var_dump($array1);

1 Comment

What is the purpose of $valuearray1 in this example?

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.