vendredi 3 mars 2017

Unique Random Integer within a For Loop

I'm trying to access 4 random entries in a nested array. So far I've come up with this code:

            $section = array_rand($acc); 

Get random array

            $index = count($acc); 

How big is the array

            echo '<ul>';
            for ($i = 0; $i < 4; $i++) { 

for() loop to get 4 of the nested arrays

                $index = rand ( 0 , $index ); 

Here is where I generate a random number to access a random nested array

                echo '<li>';
                echo '<a>'.$acc[$index]['title'].'</a>';
                echo '<div>';
                echo $acc[$index]['content'];
                echo '</div>';
                echo '</li>';
            }

End and restart for() loop 4 iterations

            echo '</ul>';
            echo '</div>';

The problem, of course, is that as every time the loop goes through it generates a random number but there is no guarantee that it won't be the same number in the previous iteration of the loop.

Is there another way to go about this?

The objective is to get 4 unique random arrays nested in a randomly selected array.




Aucun commentaire:

Enregistrer un commentaire