php Mysql 获取数组 Foreach
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16963704/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Mysql Fetch Array Foreach
提问by Brent
I am trying to use a foreach loop to set value to populate a table, for some reason my array is showing null inside values. But when I var dump the $result_list[] it shows the array of products, Am i doing this wrong? Thanks
我正在尝试使用 foreach 循环来设置值以填充表,由于某种原因,我的数组显示内部值为 null。但是当我 var dump $result_list[] 它显示产品数组时,我这样做错了吗?谢谢
$result = mysql_query("SELECT id, product, price FROM products");
$result_list = array();
while($row = mysql_fetch_array($result)) {
$result_list[] = $row;
}
foreach($result_list as $row) {
$productitems[] = array(
'id' => $row->id,
'product' => $row->product,
'price' => $row->price
);
}
var_dump($productitems);
array(2) { [0]=> array(3) { ["id"]=> NULL ["product"]=> NULL ["price"]=> NULL } [1]=> array(3) { ["id"]=> NULL ["product"]=> NULL ["price"]=> NULL } }
回答by som
foreach($result_list as $row) {
$productitems[] = array(
'id' => $row['id'],
'product' => $row['product'],
'price' => $row['price']
);
}
Try this.
尝试这个。
回答by GGio
to answer your question you are getting back row as an array and not object but yet you still try to access it as an object $row->id
. Instead use $row['id']
, $row['product']
, $row['price']
.
要回答您的问题,您将返回行作为数组而不是对象,但您仍然尝试将其作为对象访问$row->id
。而是使用$row['id']
, $row['product']
, $row['price']
。
Do not use mysql_* functions instead use PDO or MySQLi, for example look how simple it is with PDO:
不要使用 mysql_* 函数,而是使用 PDO 或 MySQLi,例如看看 PDO 是多么简单:
$productitems = $pdo->fetchAll(\PDO::FETCH_ASSOC); and then use foreach
回答by Rikesh
Change it to,
改成,
foreach($result_list as $row) {
$productitems[] = array(
'id' => $row['id'],
'product' => $row['product'],
'price' => $row['price']
);
}
Note:Please, don't use mysql_*
functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statementsinstead, and use PDO, or MySQLi- this articlewill help you decide which. If you choose PDO, here is a good tutorial.
注意:请不要mysql_*
在新代码中使用函数。它们不再被维护并被正式弃用。看到红框了吗?了解准备好的语句,并使用PDO或MySQLi-本文将帮助您决定哪个。如果您选择 PDO,这里有一个很好的教程。