简体   繁体   中英

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.

您可以通过修改查询从表中提取随机行来简化整个过程,如下所示:

SELECT icao FROM airport_list ORDER BY RAND() LIMIT 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM