【问题标题】:PHP - Get array of objects from query resultPHP - 从查询结果中获取对象数组
【发布时间】:2011-09-04 15:17:06
【问题描述】:

问题的简化版:

所以我有这个在函数内部的查询。

$query = "SELECT * FROM users";
$result = mysql_query($query);

我想如何使用 mysql_fetch_object() 从一行中获取一个对象。

因为最后我想得到一个对象数组,所以我这样做:

while ($a[] = mysql_fetch_object($result)) { // empty here }

最后这个函数只返回$a。它几乎可以正常工作。

我的问题是mysql_fetch_object最后会返回一个NULL“行”(这是正常的,因为结果结束了,但我仍然将它分配给数组)。

关于如何以体面的方式做到这一点的任何想法?提前致谢。

【问题讨论】:

    标签: php mysql arrays object


    【解决方案1】:

    或者您可以将分配从 while 条件移动到 while 主体,例如:

    <?php
    while ($entry = mysql_fetch_object($result)) {
       $a[] = $entry;
    }
    

    【讨论】:

      【解决方案2】:

      mysql_fetch_object 实际上返回 FALSE 如果没有更多的行。我会这样做:

      $a = array();
      while (($row = mysql_fetch_object($result)) !== FALSE) {
        $a[] = $row;
      }
      

      【讨论】:

      • 在 PHP 中处理布尔返回值时,我一直认为类型检查是一种很好的做法。在这种情况下,这无关紧要,但在许多其他情况下,它肯定会。这是一种防御性编程实践,IMO。
      【解决方案3】:

      你可以添加

      array_pop($a);
      

      while之后

      http://php.net/manual/en/function.array-pop.php

      【讨论】:

      • 通常不建议这样做,但由于这是循环中的退出条件,所以它会一直存在,这是一个合理的解决方案。我会添加一条评论来解释你为什么array_poping。
      【解决方案4】:

      这个问题似乎与how to fetch all the row of the result in php mysql?重复

      //Database Connection
      $sqlConn =  new mysqli($hostname, $username, $password, $database);
      
      //Build SQL String
      $sqlString = "SELECT * FROM my_table";
      
      //Execute the query and put data into a result
      $result = $this->sqlConn->query($sqlString);
      
      //Copy result into a associative array
      $resultArray = $result->fetch_all(MYSQLI_ASSOC);
      
      //Copy result into a numeric array
      $resultArray = $result->fetch_all(MYSQLI_NUM);
      
      //Copy result into both a associative and numeric array
      $resultArray = $result->fetch_all(MYSQLI_BOTH);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-06-14
        • 1970-01-01
        • 1970-01-01
        • 2012-08-22
        • 1970-01-01
        • 2010-12-16
        • 2018-06-28
        相关资源
        最近更新 更多