douweidao3882 2018-10-23 17:41
浏览 110
已采纳

foreach循环中的php mysql RAND()

I made page with all profiles. Every 3 rows I inserting a Premium block between results. I have 12 rows on page and 4 premium blocks between every 3 rows. I need to show random users with premium='1' row from mysql every foreach loop.

    $sth = $db->prepare("SELECT count(*) as premiumCount FROM users WHERE premium='1'");
    $sth->execute();
    $answer = $sth->fetch();
    $premium = $answer['premiumCount'];
    $sth2 = $db->prepare("SELECT * FROM users WHERE active='1' AND block='0' ORDER BY premium DESC LIMIT 12");
    $sth2->execute();
    $result = $sth2->fetchAll();
    foreach ($results as $answer) {
         // getting user info
       if ($premium > 0) {
            $sth = $db->prepare("SELECT * FROM users WHERE premium='1' ORDER BY RAND()");
            // getting premium user info
       }
     }

This code is work, but it can be 2-3 same premium blocks on page (I need 4 different blocks).

  • 写回答

1条回答 默认 最新

  • duanlu0075 2018-10-23 17:47
    关注

    Select as many random premium users as you need before the loop with one query (you can add LIMIT 4 to your query) instead of selecting repeatedly inside the loop. That way you can be sure you won't have duplicates.

    Fetch the results and store them in an array, and where you're running the "SELECT * FROM users WHERE premium='1'... query inside the loop, use a value from the array instead. You can use array_pop to get values so you won't have to mess with a counter or anything like that to keep track of your position in the array.

    // getting premium user info
    $sth = $db->prepare("SELECT * FROM users WHERE premium='1' ORDER BY RAND() LIMIT 4");
    $sth->execute();
    $premium = $sth->fetchAll();
    
    foreach ($results as $answer) {
         // getting user info
       if ($premium) {
            $premium_row = array_pop($premium);
       }
     }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置