Mount two-dimensional PHP array

Asked

Viewed 144 times

5

I need to mount a two-dimensional array through 2 arrays received via post.

Example of arrays I receive:

        Array
    (
        [0] => disc03
        [1] => disc04
    )


    Array
    (
        [0] => prof03
        [1] => prof04
    )

From the two, I need to assemble the following output:

Array
(
    [0] => Array
        (
            [disciplina] => disc03
            [professor] => prof03
        )

    [1] => Array
        (
            [disciplina] => disc04
            [professor] => prof04
        )

)

Basically I need to unite them where the keys are equal, but by changing the value of the key to 'discipline' and 'teacher' respectively. The goal is to make multiple Inserts in the database using an array.

(Usage Codeigniter 3)

1 answer

5


If you’re going to do this in PHP, just use array_map:

$disciplinas = ['x', 'y'];
$professores = ['1', '2'];

$resultado = array_map(function ($disciplina, $professor) {
    return compact('disciplina', 'professor');
}, $disciplinas, $professores);

print_r($resultado);

The result will be:

Array
(
    [0] => Array
        (
            [disciplina] => x
            [professor] => 1
        )

    [1] => Array
        (
            [disciplina] => y
            [professor] => 2
        )

)
  • Thank you very much Anderson! It worked perfectly!

Browser other questions tagged

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