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);
       }
     }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 关于#html5#的问题:H5页面用户手机返回的时候跳转到指定页面例如(语言-javascript)
  • ¥15 无法使用此凭据登录,因为你的域不可用,如何解决?(标签-Windows)
  • ¥15 yolov9的训练时间
  • ¥15 二叉树遍历没有报错但无法正常运行
  • ¥15 在linux系统下vscode运行robocup3d上场球员报错
  • ¥15 Python语言实验
  • ¥15 SAP HANA SQL 增加合计行
  • ¥20 用C#语言解决一个英文打字练习器,有偿
  • ¥15 srs-sip外部服务 webrtc支持H265格式
  • ¥15 在使用abaqus软件中,继承到assembly里的surfaces怎么使用python批量调动