mercredi 3 octobre 2018

Random Assoc Array Value in PHP

i have an assoc array which comes from an

mysqli_fetch_assoc() 

function. I would get a value from a random key of it...

Basically, I just need to pick an ICAO up randomly from the db.

So I've found this function

function shuffle_assoc($list) { 
    if (!is_array($list)) return $list; 

    $keys = array_keys($list); 
    shuffle($keys); 
    $random = array(); 
    foreach ($keys as $key) { 
        $random[$key] = $list[$key]; 
    }
 return $random; 
} 

And I tried to code:

$sql = "SELECT icao FROM airport_list";
$result = mysqli_query($conn, $sql);

while ($airports = mysqli_fetch_assoc($result)){
    $random_airport = shuffle_assoc($airports);
}

var_dump($random_airport);

The "var-dumped" result is

array(1) { ["icao"]=> string(4) "ZYTX" }

which seems to be an array that never changes while reloading the page, so... I think it's wrong.




Aucun commentaire:

Enregistrer un commentaire