数组还是关联?
我正在尝试将 MySQL 表中的数据存储到 PHP 数组变量中。
目前,我已经得到了这个:
$row = $db->query("SELECT * FROM settings");
$sysconfig = $row->fetch_array();
数据库方案是这样的:
property value
online 1
autoupd 1
setting 1
等等。
我应该如何编写上面的代码,以便我可以使用数据中的属性的值,即
$sysconfig['online' ]
会返回“1”?
var_dump($sysconfig)
产生这个
array(6) { [0]=> string(6) "online" ["property"]=> string(6) "online" [1]=> string(1) "1" ["propertyid"]=> string(1) "1" [2]=> string(1) "1" ["value"]=> string(1) "1" }
A print_r($sysconfig)
产生这个
Array ( [0] => online [property] => online [1] => 1 [propertyid] => 1 [2] => 1 [value] => 1 )
谢谢
I'm trying to store data from a MySQL table into an PHP array variable.
Currently, I've got this:
$row = $db->query("SELECT * FROM settings");
$sysconfig = $row->fetch_array();
the database scheme is as such:
property value
online 1
autoupd 1
setting 1
etc.
How should I write the above code, so that I can use the value, for the property in the data, i.e.
$sysconfig['online']
would return "1"?
A var_dump($sysconfig)
yields this
array(6) { [0]=> string(6) "online" ["property"]=> string(6) "online" [1]=> string(1) "1" ["propertyid"]=> string(1) "1" [2]=> string(1) "1" ["value"]=> string(1) "1" }
A print_r($sysconfig)
yields this
Array ( [0] => online [property] => online [1] => 1 [propertyid] => 1 [2] => 1 [value] => 1 )
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
fetch_array 返回关联数组和枚举数组。您可以通过添加 MYSQL_ASSOC 参数指定它仅返回 assoc 数组。或者您可以使用 fetch_assoc 方法。
UPD:对于您的方案,您只有“属性”和“值”列,因此您需要使用联接重写选择查询或迭代数据集,如下所示:
fetch_array returns both associative and enumerated arrays. You can specify it to return only assoc array by adding MYSQL_ASSOC parameter. Or you may use fetch_assoc method.
UPD: For your scheme you have only 'property' and 'value' columns, so you need to rewrite your select query with joins or iterate through dataset like this:
你使用的类是什么样的?我通常建议使用类似:
它将返回该行的数组。你的 $db 类有这个方法吗?如果执行以下操作会发生什么:
您应该看到返回数组的细分,其中将突出显示可以使用哪些方法来访问其中的数据。
编辑:
将此行替换
为:
然后您应该能够根据需要访问结果。
what does the class you're using look like? I'd usually suggest using something like:
which would return an array for that row. Does your $db class have a method for this? What happens if you do the following:
You should see a breakdown of the returned array, which will highlight which methods you can use to access the data within.
EDIT:
Replace this line:
With:
You should then be able to access the results as you wanted.