dpzr52746 2016-12-31 23:27
浏览 61
已采纳

跟踪2个关键阵列

I'm trying to implement a polling system where if the user lands on a particular poll page and actually answers the question, then the id and their option will be logged. For example, let's say the id of that question is 67 and they answered option 2, then I want the array to look something like this: 67:2. The log array data will be kept in a SESSION variable, and each time the user answers a question it'll add on to this array. When the user tries to navigate to a poll he/she answered already, then it'll display the answered option.

I know I could use concatenate and the in_array function if this was an array of only numbers, like "3,2,1,5,6" but how can I do this for this type of array? ("3:1, 2:2, 1:1") where the first digit is the id and the second digit is the option chosen. How do I use if (in_array($id)) when after concatenation it'll be something like this "3:1"?

  • 写回答

1条回答 默认 最新

  • doufei16736 2016-12-31 23:40
    关注

    I would say, you can do this way:

    // Log an answer:
    $_SESSION["polls"][$question] = $answer;
    

    This way, it will be logging:

    {
      "polls": {
        "question-6": "answer-2",
        "question-4": "answer-1"
      }
    }
    

    So there will be no duplication. To check if the user has answered already, you can do this:

    in_array("question-6", array_keys($_SESSION["polls"]))
    

    This will give you if the user has answered question 6 or not.

    PHP Script

    <?php
        header("Content-type: text/plain"); session_start();
        // Log few questions and answers.
        $question = "question-67";
        $answer = "answer-2";
        $_SESSION["polls"][$question] = $answer;
        $question = "question-55";
        $answer = "answer-1";
        $_SESSION["polls"][$question] = $answer;
        $question = "question-42";
        $answer = "answer-3";
        $_SESSION["polls"][$question] = $answer;
        // Let's check if the next question, which will be the same one, has been answered or not.
        $question = "question-67";
        $answer = "answer-2";
        if (in_array($question, array_keys($_SESSION["polls"])))
            echo "Question has been answered.";
        else
            echo "Question not answered.";
    ?>
    

    I get the output as:

    Question has been answered.
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 php 将rtmp协议转hls协议,无法播放
  • ¥15 miniconda安装不了
  • ¥20 python代码编写
  • ¥20 使用MPI广播数据遇到阻塞
  • ¥15 TinyMCE如何去掉自动弹出的“链接…”工具?
  • ¥15 微信支付转账凭证,如何解决
  • ¥15 在win10下使用指纹登录时,界面上的文字最后一个字产生换行现象
  • ¥20 使用AT89C51微控制器和MAX7219驱动器来实现0到99秒的秒表计数,有开始和暂停以及复位功能,下面有仿真图,请根据仿真图来设计c语言程序
  • ¥15 51单片机 双路ad同步采样
  • ¥15 使用xdocreport 生成word