dousu8456 2018-10-03 07:31
浏览 96
已采纳

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.

  • 写回答

1条回答 默认 最新

  • douzinei6926 2018-10-03 07:40
    关注

    You can simplify this whole process by pulling a random row from the table by amending your query as can be seen below:

    SELECT icao FROM airport_list ORDER BY RAND() LIMIT 1
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部