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?
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?
– Marcos Vinicius
@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...
– Augusto Vasques
..., 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.– Augusto Vasques