需要帮助来理解 PDO 的结果集
我有以下函数执行 PDO 查询:
// removed error handling for presenting here
function getRows($sql) {
$stmt = $this->db->query($sql);
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $result;
}
}
结果是:
Array
(
[0] => Array
(
[id] => 1
[category] => Audi
)
[1] => Array
(
[id] => 2
[category] => BMW
)
[2] => Array
(
[id] => 3
[category] => Chrysler
)
)
以下 foreach
代码:
foreach($result as $key => $value ) {
echo $value.'<br/>';
}
输出:
Array
Array
Array
我该怎么做才能返回以下内容?
Audi
BMW
Chrysler
我知道我可以这样做 $value['category]
。
但这不是我想要实现/理解的。我希望结果集不成为数组的数组。
I have the following function executing PDO queries:
// removed error handling for presenting here
function getRows($sql) {
$stmt = $this->db->query($sql);
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $result;
}
}
The result is:
Array
(
[0] => Array
(
[id] => 1
[category] => Audi
)
[1] => Array
(
[id] => 2
[category] => BMW
)
[2] => Array
(
[id] => 3
[category] => Chrysler
)
)
The the following foreach
code:
foreach($result as $key => $value ) {
echo $value.'<br/>';
}
outputs this:
Array
Array
Array
What can I do so it returns the following?
Audi
BMW
Chrysler
I understand that I could just do $value['category]
.
But that's not what I want to achieve / understand. I would like the resultset not to be an array of arrays.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试
替代方案
try
Alternative
foreach 循环将数组拆分为键值对。循环中的键是数组的索引,值是包含 ID 和 Category 的数组。
要访问该类别,只需执行以下操作:
The foreach loop splits up your array into key, value pairs. The key in your loop is the index of the array, the value is an array containing ID and Category.
To access the category simply do: