First array element of a multidimensional array as key for others

0

I'm reading an Excel worksheet that returns a result like the one 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 array element, which is always the same, as the key to the other arrays? getting like this:

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

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

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

)
    
asked by anonymous 25.04.2018 / 06:17

1 answer

1

Yes, you only have to retrieve the first element:

$chaves = $retorno[0];

Then go through the array starting from the first index and add it 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
        )

)

See working at ideone.com

    
25.04.2018 / 06:33