-2

I have an Array like this

        $array1 = [
            0 => [
                'category_name' => 'Example 1'
            ],
            1 => [
                'category_name' => 'Example 2'
            ],
            2 => [
                'category_name' => 'Example 3'
            ],
        ];

I want to add more keys in each index of this array and finally I want to get output like this

        $array2 = [
            0 => [
                'import_id' => 10,
                'country_id' => 1,
                'category_name' => 'Example 1'
            ],
            1 => [
                'import_id' => 10,
                'country_id' => 1,
                'category_name' => 'Example 2'
            ],
            2 => [
                'import_id' => 10,
                'country_id' => 1,
                'category_name' => 'Example 3'
            ],
        ];

But I don't want to use any loop to do this. is it possible ??

3
  • You can't add values to subarrays without loopin outer array. So, loop, it's not a rocketscience. Commented Apr 24, 2020 at 16:15
  • In any case it will be a loop, even if you use array_map or something else Commented Apr 24, 2020 at 16:16
  • The only way to do it without loop is to hardcode it. Commented Apr 24, 2020 at 16:19

1 Answer 1

0

One long way without using a loop :)

    $array2 = array_fill(0, count($array1), ['import_id' => 10, 'country_id' => 1]);
    $array2 = array_replace_recursive($array2, $array1);

demo

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.