Iterate an array to the end from a randomly generated index - PHP/Laravel

Asked

Viewed 47 times

0

Good evening, everyone.

I have an array with some bus stops with the following information:

array:9 [▼
0 => array:4 [▼
"id" => 35
"nome" => "Parada 35 - Copacabana"
"endereco_completo" => "Rua Copacabana"
"tempo" => 5
]
1 => array:4 [▼
"id" => 36
"nome" => "Parada 36 - Copacabana"
"endereco_completo" => "Rua Copacabana"
"tempo" => 11
]
2 => array:4 [▼
"id" => 37
"nome" => "Parada 37 - Copacabana"
"endereco_completo" => "Rua Copacabana"
"tempo" => 7
]
3 => array:4 [▼
"id" => 38
"nome" => "Parada 38 - Boa Viagem"
"endereco_completo" => "Rua Vinte de Janeiro"
"tempo" => 12
]
4 => array:4 [▼
"id" => 39
"nome" => "Parada 39 - Boa Viagem"
"endereco_completo" => "Rua Vinte de Janeiro"
"tempo" => 6
]
5 => array:4 [▼
"id" => 40
"nome" => "Parada 40 - Boa Viagem"
"endereco_completo" => "Rua Barão de Souza Leão"
"tempo" => 7
]
6 => array:4 [▼
"id" => 41
"nome" => "Parada 41 - Boa Viagem"
"endereco_completo" => "Rua Barão de Souza Leão"
"tempo" => 7
]
7 => array:4 [▼
"id" => 42
"nome" => "Parada 42 - Boa Viagem"
"endereco_completo" => "Rua Barão de Souza Leão"
"tempo" => 11
]
8 => array:4 [▼
"id" => 43
"nome" => "Parada 43 - Boa Viagem"
"endereco_completo" => "Rua Barão de Souza Leão"
"tempo" => 11
]

My first goal is to select a stop randomly in this array. After selected, I want to take the sum of the times of each stop from this randomly selected stop (ignoring the previous ones).

I’m doing the following to select this random stop:

foreach ($arrayParadas as $key => $value) {
        $pegarParadaRandomica = rand($key, 1);
    }

With this I have the index of the array of a random stop, but I’m not able to do the rest.

1 answer

1


To select the stop where you will start just use the rand(that you were already using) 0 to the length of the stops minus one, which will give you the starting position:

$indiceParadaInicial = rand(0, count($arrayParadas) - 1);

The second parameter must be tamanho-1 because the end value is for randomic generation is inclusive, and as we are generating positions, the position corresponding to the size would already be outside the array.

Then just use a for normal, since its array is composed of numeric indices starting at 0.

Example:

$tempoTotal = 0;

for ($i = $indiceParadaInicial; $i < count($arrayParadas); ++$i){
    $tempoTotal += $arrayParadas[$i]["tempo"];
}

See this example in Ideone

  • That’s exactly what I’ve been wanting to do, very nice your answer Isac, thanks

Browser other questions tagged

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