【发布时间】:2015-07-11 13:10:11
【问题描述】:
我有一个 mysql 查询,它从数据库中获取许多行,我想将这些结果绑定到一个多维数组中。
$sample = array();
$samples = array();
//bind results into $sample array
$stmt->bind_result($sample['id'], $sample['name'], $sample['image_path'],
$sample['main_text'], $sample['nose'], $sample['palate'], $sample['finish'],
$sample['sample_price'], $sample['retail_price'], $sample['retail_url']);
//fetch each row of results and push the resultant array into the $samples array
while($stmt->fetch()) {
$samples[] = $sample;
}
这是我希望上述实现的伪代码实例:
$samples = array(
0 => array(
"id" => the item's id
"name" => the item's name
"image_path" => the item's image pgae
"main_text" => the second item's main text
"nose" => etc
"finish" => etc
"palate" => etc
"sample_price" => etc
"retail_url" => etc
1 => array(
"id" => the second item's id
"name" => the second item's name
"image_path" => the second item's image page
"main_text" => the second item's main text
"nose" => etc
"finish" => etc
"palate" => etc
"sample_price" => etc
"retail_url" => etc
相反,我最终得到了一个包含相同项目的多维数组。更具体地说,如果我单步执行代码:
- 列表中的第一项很好
- 第二项进入数组,第一项成为第二项的副本
- 第三项进入数组,第一项和第二项成为第三项的副本 等
我的假设是 $sample 以某种方式通过引用被推送到数组中,但这对我来说没有意义,因为 php 按值分配数组。
有人知道我做错了什么吗?
更新:我知道 get_result() 函数。不幸的是,这只有在使用 MySQL 原生驱动程序编译 mysqli 扩展时才有效——这是很难保证的。
【问题讨论】:
-
你查看我的更新了吗?
-
@Alex 是的,我刚刚这样做了。效果很好,谢谢:)。出于兴趣,我想知道您能否告诉我为什么我的原始代码不起作用?
标签: php mysql arrays multidimensional-array mysqli