dousu8456 2018-10-03 15: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 15: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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 chaquopy python 安卓
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 CSS实现渐隐虚线框
  • ¥15 有没有帮写代码做实验仿真的
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥30 vmware exsi重置后登不上
  • ¥15 易盾点选的cb参数怎么解啊
  • ¥15 MATLAB运行显示错误,如何解决?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容