这个问题与上一个问题有关:PDO, MySQL - How do I return an array from a function?
但我觉得不够具体。
我想在数组中以自己的键返回每行变量,以便我可以在调用程序中使用它们。
这是我到目前为止的代码,但不确定它是否正确,甚至是否朝着正确的方向发展:
$total = $dbh->prepare("SELECT COUNT(post_id) FROM mjbox_posts");
$stmt = $dbh->prepare("SELECT * FROM mjbox_images JOIN mjbox_posts USING (post_id) WHERE post_id = ?");
$stmt->bindParam(1,$post_id);
$stmt->execute();
$resultarray = array();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
for($i=0;$i<=$total;$i++){
$resultarray[] = array("id"=>$row['img_id'],"filename"=>$row['img_file_name']);
}
}
return $resultarray;
看起来数据确实被插入到数组中并传递回调用程序,但它似乎在数组中复制了每条数据两次:
Array ( [0] => Array ( [0] => Array ( [id] => 5 [filename] => fullsize/8520430289728860armor.jpg ) [1] => Array ( [id] => 5 [filename] => fullsize/8520430289728860armor.jpg ) [2] => Array ( [id] => 6 [filename] => fullsize/5535575154865203bg1.jpg ) [3] => Array ( [id] => 6 [filename] => fullsize/5535575154865203bg1.jpg ) [4] => Array ( [id] => 7 [filename] => fullsize/7598226850012898images.jpg ) [5] => Array ( [id] => 7 [filename] => fullsize/7598226850012898images.jpg ) ) )