doulandai0641 2019-03-06 18:18
浏览 67
已采纳

SQL数组显示在没有SQL查询的行中

I am trying to test a few scripts that I would normally get from an SQL database but for testing offline I am just creating an array.

Here is what I have right now;

$result = array
(
    array("name"=>"Toby", "q1"=>"1"),
    array("name"=>"Phelps", "q1"=>"1"),
    array("name"=>"Davies", "q1"=>"1"),
    array("name"=>"Keith", "q1"=>"1"),
);

$resultnum = count($result);
echo "<b>Question 1</b> <br/><br/>";
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $name = $row['name'];
        $answer = $row['q1'];

        $q1answer = 1;

        if($answer == $q1answer) {
            echo $name . " got this right! <br/>";
        } else {
            echo $name . " got this wrong! <br/>";
        }

    }
}

How can I get this to work the same as though it was getting the array from an SQL query instead of just my array, for some reason I can't find a way to get this to run.

  • 写回答

2条回答 默认 最新

  • dongxiezhi9564 2019-03-06 18:43
    关注

    Similar to the earlier answer, I propose a class. Here I would actually name the class, and pass the data to the constructor. The iteration over the array can be done with the current and next methods:

    class ResultSet {
        private $array = [];
        public $num_rows = 0;
        public function __construct($data) {
            $this->array = $data;
            $this->num_rows = count($this->array);
        }
        public function fetch_assoc() {
            $val = current($this->array);
            next($this->array);
            return $val;
        }
    }
    

    Until there it would be fixed. You would play with the data in the following:

    $result = new ResultSet([
            ["name"=>"Toby",   "q1"=>"1"],
            ["name"=>"Phelps", "q1"=>"1"],
            ["name"=>"Davies", "q1"=>"1"],
            ["name"=>"Keith",  "q1"=>"1"],
        ]);
    

    I did not implement support for count($result) as I don't think that is supported on real mysqli result sets either. You get the count via ->num_rows (like you also do).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试
  • ¥20 问题请教!vue项目关于Nginx配置nonce安全策略的问题