Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
311 views
in Technique[技术] by (71.8m points)

php - 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.

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
)

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?

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();              

}

The first array inserts fine, however the last array inserts zeros for the staffID.

Any suggestions?

Thanks =).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...