First element array of a multidimensional array as key for others

Asked

Viewed 75 times

0

I am reading an Excel spreadsheet that returns a result like the below, the first array being the name of the columns

Array
(
    [0] => Array
        (
            [0] => nome
            [1] => sobre_nome
        )

    [1] => Array
        (
            [0] => nome1
            [1] => snome1
        )

    [2] => Array
        (
            [0] => nome2
            [1] => snome2
        )

    [3] => Array
        (
            [0] => nome3
            [1] => snome3
        )

)

Is there any practical way to use the first element array, which is always the same, as a key for other arrays? getting this way:

Array
(
    [0] => Array
        (
            [nome] => nome1
            [sobre_nome] => snome1
        )

    [1] => Array
        (
            [nome] => nome2
            [sobre_nome] => snome2
        )

    [2] => Array
        (
            [nome] => nome3
            [sobre_nome] => snome3
        )

)
  • It would also be good to put as you are creating this array, as it would be more convenient to return the array as you want instead of going through it all and creating another array.

1 answer

1

Yes, just you retrieve the first element:

$chaves = $retorno[0];

then go through the array starting from the first index and add to the new array:

$novo = [];
for($i=1; $i < count($retorno); $i++){
  $novo[] = [
    $chaves[0] => $retorno[$i][0],
    $chaves[1] => $retorno[$i][1]
  ];
}

you will get the desired return:

Array
(
    [0] => Array
        (
            [nome] => nome1
            [sobre_nome] => snome1
        )

    [1] => Array
        (
            [nome] => nome2
            [sobre_nome] => snome2
        )

    [2] => Array
        (
            [nome] => nome3
            [sobre_nome] => snome3
        )

)

Behold working on ideone.com

Browser other questions tagged

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