How to connect two arrays?

Asked

Viewed 141 times

2

If I have an array:

Array
(
    [0] => Array
        (
            [color] => azul
        )
    [1] => Array
        (
            [color] => branca
        )
    [2] => Array
        (
            [color] => prata
        )
    [3] => Array
        (
            [color] => preta
        )
    [4] => Array
        (
            [color] => roxa
        )
    [5] => Array
        (
            [color] => vermelha
        )
)

And another:

Array
(
    [0] => Array
        (
            [COUNT(color)] => 3
        )
    [1] => Array
        (
            [COUNT(color)] => 1
        )
    [2] => Array
        (
            [COUNT(color)] => 1
        )
    [3] => Array
        (
            [COUNT(color)] => 6
        )
    [4] => Array
        (
            [COUNT(color)] => 1
        )
    [5] => Array
        (
            [COUNT(color)] => 6
        )
)

And I want to interact with them Leaving them like this:

Array
(
    [0] => Array
        (
            [color] => azul
            [COUNT(color)] => 3
        )
    [1] => Array
        (
            [color] => branca
        )
    [2] => Array
        (
            [color] => prata
            [COUNT(color)] => 3
        )
    [3] => Array
        (
            [color] => preta
            [COUNT(color)] => 3
        )
    [4] => Array
        (
            [color] => roxa
            [COUNT(color)] => 3
        )
    [5] => Array
        (
            [color] => vermelha
            [COUNT(color)] => 3
        )
)

Or maybe otherwise because I need to use both values in 1 foreach declaring, (color name) and next (quantity).

  • In php? which language?

  • What language would that be?

  • Ah forgot to say PHP

1 answer

1

<?php
$x = Array(0 => Array('a' => 'b'), 1 => Array('c' => 'd'));
$y = Array(0 => Array('e' => 'f'), 1 => Array('g' => 'h'));

var_dump(array_map(array_merge, $x, $y));
?>

Exit:

array(2) {
  [0]=>
  array(2) {
    ["a"]=>
    string(1) "b"
    ["e"]=>
    string(1) "f"
  }
  [1]=>
  array(2) {
    ["c"]=>
    string(1) "d"
    ["g"]=>
    string(1) "h"
  }
}

What we want to do with each element of the individual arrays is array_merge (which combines the keys of both dictionaries); array_map apply array_merge to each element of both arrays individually and returns the answer.

  • ta me returning this: " Notice: Use of Undefined Constant array_merge - assumed 'array_merge' "I’ll see here q can be

  • Did you run exactly the code I wrote, or did you adapt it in your code? Can you tell the version of your PHP?

  • I adapted, but in the same way that you wrote the same error. I only put array_map(array_merge, $x, $y)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.