PDO fetchAll 数组到一维

问题描述 投票:0回答:3

这可能是一个简单的问题,但我很难理解如何解决它。我有一个表格,允许用户选择“自定义”或“所有”员工”来分配工作。

如果选择自定义,用户通过单击每个复选框来选择员工,然后我将它们插入到职位表中。这会生成下面的数组(3、1、10 是员工 ID)

Array
(
    [0] => 3
    [1] => 1
    [2] => 10
)

如果选择“所有员工”,我首先查询 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
        )
)

如何将上面的数组转换为显示的第一个数组?

我使用下面的代码查询数据库以获取所有员工 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();              

}

第一个数组插入正常,但最后一个数组为 StaffID 插入零。

有什么建议吗?

谢谢=)。

php arrays pdo
3个回答
121
投票

霍雷肖

As thou art to thyself:
Such was the very armour he had on
When he the ambitious Norway combated;
So frown'd he once, when, in an angry parle,
He smote the sledded Polacks on the ice.
'Tis strange.

马塞勒斯

Thus twice before, and jump at this dead hour,
With martial stalk hath he gone by our watch.

霍雷肖

In what particular thought to work I know not;
But in the gross and scope of my opinion,
This bodes some strange eruption to our state.

马塞勒斯

Good now, sit down, and tell me, he that knows,
Why this same strict and most observant watch
So nightly toils the subject of the land,
And why such daily cast of brazen cannon,
And foreign mart for implements of war;
Why such impress of shipwrights, whose sore task
Does not divide the Sunday from the week;
What might be toward, that this sweaty haste
Doth make the night joint-labourer with the day:
Who is't that can inform me?

3
投票

如果您

print_r($staff[$i])
for
内,您可能会得到

    Array
    (
        [staffID] => 1
        [0] => 1
    )

这意味着您应该使用

$staff[$i]['staffID']
来代替。


另一种选择,应该适用于您当前的代码,是使用

PDOStatement::fetchColumn()
而不是
fetchAll()


2
投票

你需要给 fetchAll 一个 fetch 样式

$staff = $select->fetchAll(PDO::FETCH_NUM);

来自此链接

© www.soinside.com 2019 - 2024. All rights reserved.