简体   繁体   English

PHP - 从查询结果中获取对象数组

[英]PHP - Get array of objects from query result

Simplified version of the problem:问题的简化版本:

So I have this query which is inside a function.所以我有这个查询,它位于 function 内。

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

How I want to use mysql_fetch_object() to get an object from a row.我想如何使用 mysql_fetch_object() 从一行中获取 object。

Because in the end I wanted to get an array of objects I do this:因为最后我想得到一个对象数组,所以我这样做:

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

In the end the function just returns $a.最后 function 只返回 $a。 And it works almost fine.它几乎可以正常工作。

My problem is that mysql_fetch_object will return at the end a NULL "row" (which is normal because the result ended but I still assigned it to the array).我的问题是 mysql_fetch_object 将在最后返回一个 NULL “行”(这是正常的,因为结果结束但我仍然将它分配给数组)。

Any ideas on how to do this in a decent way?关于如何以体面的方式做到这一点的任何想法? Thanks in advance.提前致谢。

Or you could move the assignment from the while condition to the while body like:或者您可以将分配从 while 条件移动到 while 主体,例如:

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

mysql_fetch_object actually returns FALSE if there are no more rows.如果没有更多行, mysql_fetch_object实际上会返回FALSE I would do this:我会这样做:

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

This question seems like duplicate of how to fetch all the row of the result in php mysql?这个问题似乎与如何在 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);

You can just add你可以添加

array_pop($a);

after the while过了一会while

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM