Use an array as key for another associative array

0

I have these two arrays in php:

Array
(
    [0] => nome
    [1] => cargo
    [2] => email
)



Array
(
    [0] => Array
        (
            [0] => nome1
            [1] => cargo1
            [2] => [email protected]
        )

    [1] => Array
        (
            [0] => nome2
            [1] => cargo2
            [2] => [email protected]
        )
)

I wanted to combine the two so that the result would be as follows:

Array
(
    [0] => Array
        (
            [nome] => nome1
            [cargo] => cargo1
            [email] => [email protected]
        )

    [1] => Array
        (
            [nome] => nome2
            [cargo] => cargo2
            [email] => [email protected]
        )

)

Any ideas how I can do this?

    
asked by anonymous 22.06.2017 / 12:49

1 answer

1

Here's a way to create the structure you mentioned, commented code:

<?php

// Item para ser o indíce no novo array
$keys =  array( "nome", "cargo", "email" );

// Valores...
$values = array(
    array("nome1", "cargo1", "[email protected]"),
    array("nome2", "cargo2", "[email protected]"),
);

// Item que armazenará o novo array
$newValues = array();

// Percorre os valores
foreach($values as $value)
{
    // Array temporário
    $tmp = array();

    // Percorre as chaves
    foreach($keys as $_key => $newKey)
    {
        // Define o indice do array de acordo com o valor de $keys
        // e define o valor buscando de $value passando o indíce numerico
        $tmp[$newKey] = $value[$_key];
    }

    // Insere o objeto no array de saída
    $newValues[] = $tmp;
}

print_r($newValues);

?>

Result:

Array
(
    [0] => Array
        (
            [nome] => nome1
            [cargo] => cargo1
            [email] => [email protected]
        )

    [1] => Array
        (
            [nome] => nome2
            [cargo] => cargo2
            [email] => [email protected]
        )

)
    
22.06.2017 / 13:10