使用 PHP 和 MongoDB 获取随机记录并以特定格式显示 [英] Getting random records and display in particular format using PHP and MongoDB

查看:71
本文介绍了使用 PHP 和 MongoDB 获取随机记录并以特定格式显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含 100 个问题和多个答案的数据库.我想以测验格式显示,一次选择 20 个随机问题.我在下面做了这样的事情

I have a DB with 100 questions and multiple answers for it. I wanted to display in a quiz format selecting 20 random questions at a time. I have done something like this below

$m=new MongoClient(); 
  $db=$m->mydb; 
  $c=$db->quiz; 
 $cursor = $c->find()
      $n = 20;
            foreach ($cursor as $obj) { 
             $links=array('$obj["question"]<br><br> &nbsp;&nbsp;&nbsp;&nbsp;
                                                    <input type="radio" name="q1" value="$obj["ch1"]"> $obj["ch1"]<br>&nbsp;&nbsp;&nbsp;&nbsp;
                                                    <input type="radio" name="q1" value="$obj["ch2"]"> $obj["ch2"]<br>&nbsp;&nbsp;&nbsp;&nbsp; 
                                                  <input type="radio" name="q1" value="$obj[ch3"]"> $obj["ch3"]</p>');

    $rand_keys = array_rand($links, $n);
    echo "<center>". "<br><table><tr><td>";

    echo "1.&nbsp;&nbsp;". $links[$rand_keys[0]] . "<br>";
    echo "</td></tr><tr><td>";
    echo "2.&nbsp;&nbsp;".$links[$rand_keys[1]] . "<br>";
    echo "</td></tr><tr><td>";
    echo "3.&nbsp;&nbsp;". $links[$rand_keys[2]] . "<br>";
    echo "</td></tr><tr><td>";


    }

它不起作用.代码有什么问题吗?请帮助我找出错误以使其正常工作或任何可以实现我的目的的方法.

It is not working. Is there anything wrong with th code? Please help me either finding the wrong to make it work or any method that would achieve my purpose.

推荐答案

好的,考虑到其他非重复问题,我建议单独学习 php 基础知识并尝试迭代硬编码的嵌套数组打印预期的输出.

OK, considering other non-duplicated questions, I would recommend to learn basics of php alone and try to iterate a hardcoded nested array to print expected output.

所以问题中的代码存在一些问题:

So some problems with the code in the question:

  • 它不会提取随机问题
  • 它只打印 1 个长字符串到 links 数组.请了解 '"
  • 没有循环来迭代答案,它根本不是有效的 php 代码
  • it does not fetch random questions
  • it prints nothing but adds 1 long string to links array. Please learn difference between ' and "
  • there is no loop to iterate answers, and it is not valid php code at all

工作代码(再次考虑来自非重复问题的文档结构>) 可能看起来像:

The working code (again considering document structure from non-duplicated question) may look like:

foreach ($cursor as $obj) { 
    echo $obj["question"];
    foreach($obj["answers"] as $key=>$answer) {
        echo '<input type="radio" name="' . $key . '" value="'.$answer.'">';
    }
}

这篇关于使用 PHP 和 MongoDB 获取随机记录并以特定格式显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆