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

0

Good evening guys.

I have an array with a few 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 goal is to randomly select a stop in this array. After selected, I want to get the sum of the times of each one stopped 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 array index of a random stop, but I can not do the rest.

    
asked by anonymous 03.06.2018 / 00:56

1 answer

1

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

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

It is necessary that the second parameter be tamanho-1 because the end value is for random generation is inclusive, and since we are generating positions, the position corresponding to the size would already be outside the array.

Then just use a for normal, since your array is made up of numerical indices beginning with 0 .

Example:

$tempoTotal = 0;

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

See this example in Ideone

    
03.06.2018 / 01:27