PDO fetchAll 数组到一维 [英] PDO fetchAll array to one dimensional
问题描述
这可能是一个简单的问题,但我正在努力理解如何解决它.我有一个表单,允许用户选择自定义"或所有"员工来分配给工作.
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.
如果选择自定义,用户通过单击每个复选框来选择员工,然后我将这些插入到工作表中.这会产生下面的数组(3、1、10 是员工 ID)
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)
Array
(
[0] => 3
[1] => 1
[2] => 10
)
如果选择了所有员工",我首先查询一个选择语句,从员工表中获取所有员工 ID,然后将这些插入到工作表中,与上面相同.但是这会产生数组:
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 :
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?
我正在使用下面的代码查询数据库以获取所有员工 ID,然后将其插入.
I'm using the code below to query the database to get all the staff ID's and then inserting them.
$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();
}
第一个数组插入正常,但最后一个数组为员工 ID 插入零.
The first array inserts fine, however the last array inserts zeros for the staffID.
有什么建议吗?
谢谢=)
推荐答案
看一看 手册中的示例 2.在您的第一个查询中,您可以使用:
Take a look at example 2 in the manual. In your first query you can use:
$staff = $select->fetchAll(PDO::FETCH_COLUMN, 0);
您的第二个数组将与第一个数组具有相同的形式.
And your second array will have the same form as the first array.
这篇关于PDO fetchAll 数组到一维的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!