将 php 结果集转换为数组
我正在尝试将 php 结果集转换为数组(使用 foreach),我做得不太正确..
我有一个结果集:
$result
我如下循环遍历它:(严重错误)
while($row = mysql_fetch_array($result)) {
foreach (mysql_fetch_array($result) as $k => $v) {
echo "Fred's $k is ". $v['uid']. "\n";
}
}
我希望这个数组位于以下格式:
Array
(
[0] => Array //row1
(
[column1] => value
[column2] => value
[column3] => value
.
.
)
[1] => Array //row2
(
[column1] => value
[column2] => value
[column3] => value
.
.
)
[2] => Array //row3
(
[column1] => value
[column2] => value
[column3] => value
.
.
)
)
我是新手,请帮忙。
I am trying to convert a php resultset into an array (using foreach), I'm not quite doing it right..
I have a resultset:
$result
I am looping through it as below: (horribly wrong)
while($row = mysql_fetch_array($result)) {
foreach (mysql_fetch_array($result) as $k => $v) {
echo "Fred's $k is ". $v['uid']. "\n";
}
}
I want this array to be in the below format:
Array
(
[0] => Array //row1
(
[column1] => value
[column2] => value
[column3] => value
.
.
)
[1] => Array //row2
(
[column1] => value
[column2] => value
[column3] => value
.
.
)
[2] => Array //row3
(
[column1] => value
[column2] => value
[column3] => value
.
.
)
)
I am a newbie, please help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
你不需要 foreach 来做到这一点,你可以坚持使用 while 循环:
然后你可以像普通数组一样使用它:
You don't need a foreach to do this, you can just stick with your while loop:
Then you can use it like a normal array:
我不太明白但是
希望这对您有帮助:
i can't understand well but
hope this will help you :
试试这个,
Try this,
尝试使用 mysql_fetch_assoc 代替:
Try mysql_fetch_assoc instead:
如此处所示,您不需要调用获取函数来访问结果集值。
假设结果集中有行,这将生成关联数组的索引数组。
如果您想选择输出数组中包含哪些列,则可以使用关联数组语法来引用数据库表的列名称 (
$row['column_a']
) 来访问它们。如果您希望所有内容都进入数组,那么您可以使用 mysqli 的 fetch_all() 来跳过手动循环。
As demonstrated here, you do not need to call a fetching function to access the result set values.
Assuming you have rows in your result set, this will generate an indexed array of associative arrays.
If you want to be selective about which columns are included in your output array, then you can access them by using associative array syntax to refer to the db table's column names (
$row['column_a']
).If you want EVERYTHING to go into your array, then you can using mysqli's
fetch_all()
to skip the manual loop.