convert one-dimensional array to associative multidimensional

Asked

Viewed 114 times

1

my problem was to convert an array into a single array in a multidimensional associative array,:

$dados = array(1,"1minuto","seco",2,"3minutos","chuva");

as you can see are three types of data that repeat, the keys are: back, weather, weather.

I tried using the array_fill_keys(), but it is necessary that the number of keys is equal to the number of items. I solved the problem as follows:

insira
 <?php

$dados = array(1,"1m","seco",2,"3m","chuva");
$i = 0;
$a = 0;
foreach($dados as $dado){

if($i === 0){
    $array[$a]['volta'] = $dado;
    $i++;

}elseif($i === 1){
    $array[$a]['tempo'] = $dado;
    $i++;
}elseif($i === 2){
    $array[$a]['clima'] = $dado;
    $i = 0;
    $a++;
}

}   
echo "<pre>";
print_r($array);
echo "</pre>";

That solved my problem, but the question is, is there any function that would solve this without needing all this gymnastics? or even a way to optimize this code?

2 answers

3


Use the function array_chunk() to divide an array into smaller arrays whose length is a given number and function array_combine() to combine two arrays where one originates the keys and the other the values:

<?php
$dados = [1, "1m", "seco", 2, "3m","chuva"];
$chaves = ["volta", "tempo", "clima"];
$resultado = [];

//Divide $dados em arrays de três elementos
foreach(array_chunk($dados, 3) as $valores){
  //Combina os valores com suas respectivas chave em um novo array e o adiciona ao resultado
  $resultado[] = array_combine($chaves, $valores);
}

print_r($resultado);

Resulting:

Array
(
    [0] => Array
        (
            [volta] => 1
            [tempo] => 1m
            [clima] => seco
        )

    [1] => Array
        (
            [volta] => 2
            [tempo] => 3m
            [clima] => chuva
        )

)

Running on Repli.it: https://repl.it/repls/YummyFeistyAlgorithm

  • thanks for the help, in fact it works, you can say if there is any performance gain using array_chunck instead of for() as the colleague replied?

  • @Marcosvinicius, If you want an answer open another question, because time complexity of algorithms is a vast subject. Above, in this case the two algorithms are linear time because they operate through all the elements of the input. The difference in cycles is minimal you have to receive an absurdly large input to feel the difference...

  • ..., but in general the rule (both algorithms are optimized to the maximum) is that a code packaged in a single for is faster than one whose function calls require an extra cycle to negotiate with the function call stack. But this difference would be felt when the entry is of the order of TB and HB. For small entries is indifferent.

2

You can do it in a simpler way using for:

$dados = array(1,"1minuto","seco",2,"3minutos","chuva");
for($x = $index = 0; $x < sizeof($dados); $x+=3, $index++){
   $array[$index]['volta'] = $dados[$x];
   $array[$index]['tempo'] = $dados[$x+1];
   $array[$index]['clima'] = $dados[$x+2];
}
echo "<pre>";
print_r($array);
echo "</pre>";

Exit:

inserir a descrição da imagem aqui

Testing at IDEONE

  • thanks for the help, in fact this way simplified the process.

  • 1

    I did not make this remark before because I did not want to influence the opinion of the AP but this answer I understand as good, I did not understand why it was flagged as low quality. The author of the signage could clarify the reason for its classification?

  • @Augustovasques Man, unfortunately here is full of terrorists.

Browser other questions tagged

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