php PDO fetchAll 数组到一维
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6047724/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PDO fetchAll array to one dimensional
提问by Elliott
this may be a simple question but am struggling to understand how to solve it. I have a form which allows the user to select either "custom" or "all" staff" to assign to a job.
这可能是一个简单的问题,但我正在努力理解如何解决它。我有一个表单,它允许用户选择“自定义”或“所有”员工来分配给工作。
If custom is selected the user selects staff by clicking each checkbox, I then insert these into a jobs table. This produces the array below (3, 1, 10 are the staff IDs)
如果选择自定义,用户通过单击每个复选框来选择员工,然后我将这些插入到工作表中。这会产生下面的数组(3、1、10 是员工 ID)
Array
(
[0] => 3
[1] => 1
[2] => 10
)
If "all staff" is selected, I first query a select statement to get all the staff ID's from the staff table, and then insert these into the job table the same as above. However this produces the array :
如果选择“所有员工”,我首先查询一个 select 语句以从员工表中获取所有员工 ID,然后将这些插入到工作表中,与上面相同。但是,这会产生数组:
Array
(
[0] => Array
(
[staffID] => 1
[0] => 1
)
[1] => Array
(
[staffID] => 23
[0] => 23
)
[2] => Array
(
[staffID] => 26
[0] => 26
)
[3] => Array
(
[staffID] => 29
[0] => 29
)
)
How can I convert the array above to the first array shown?
如何将上面的数组转换为显示的第一个数组?
I'm using the code below to query the database to get all the staff ID's and then inserting them.
我正在使用下面的代码查询数据库以获取所有员工 ID,然后插入它们。
$select = $db->prepare("SELECT staffID FROM staff");
if($select->execute())
{
$staff = $select->fetchAll();
}
for($i = 0; $i<count($staff); $i++)
{
$staffStmt = $db->prepare("INSERT INTO staffJobs (jobID, userID) VALUES (:jobID, :staffID)");
$staffStmt->bindParam(':jobID', $jobID, PDO::PARAM_INT);
$staffStmt->bindParam(':staffID', $staff[$i], PDO::PARAM_INT);
$staffStmt->execute();
}
The first array inserts fine, however the last array inserts zeros for the staffID.
第一个数组插入正常,但最后一个数组为人员 ID 插入零。
Any suggestions?
有什么建议?
Thanks =).
谢谢=)。
回答by jeroen
回答by chelmertz
If you print_r($staff[$i])
inside the for
you would probably get
如果你print_r($staff[$i])
在里面,for
你可能会得到
Array
(
[staffID] => 1
[0] => 1
)
which means you should use $staff[$i]['staffID']
instead.
这意味着您应该$staff[$i]['staffID']
改用。
The other alternative, which should work with your current code, is to use PDOStatement::fetchColumn()
instead of fetchAll()
.
另一种适用于您当前代码的PDOStatement::fetchColumn()
替代方法是使用代替fetchAll()
.