Use an array as a key for another associative array

Asked

Viewed 100 times

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 idea how I can do this?

1 answer

1


Follows a way to create the structure you quoted, 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);

?>

Upshot:

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

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

)
  • I don’t think you understand my question, this will combine the two but that’s not what I want...

  • Really, I had not understood. I woke up now.. kkk I will adjust

  • 1

    I’ve adjusted the code now to what you need. P

  • Perfect, that’s right. Thank you

Browser other questions tagged

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