Dog
Dog

Reputation: 339

Array outcome from foreach loop from SQL Query

Looking for the code below to create an array of 1's and 0's from this query. At the moment, the result from $rows is:

Array ( [discontinued] => 1, ) Array ( [discontinued] => 1 ) Array ( [discontinued] => 0 ) Array ( [discontinued] => 0 ) Array ( [discontinued] => 1 ).... 

where I would rather have something like:

Array [1] => 1 [2] => 1 [3] => 0 [4] => 0 [5] => 1....

Anyone could help me out on this, it would be greatly appreciated. Please don't comment about vulnerabilities in the code; I know it's already there. I am just a beginner...I just want the core guts of it to work.

Cheers! :)

function checkDiscontinued($dbh, $idDiscontinuedArray) {
try {
    foreach ($idDiscontinuedArray as $id) {

        $stmt = $dbh->query("SELECT discontinued FROM `$id` ORDER BY `date` DESC LIMIT 1");
        $rows = $stmt->fetch(PDO::FETCH_ASSOC);

        print_r($rows);

        }
        if ($rows['discontinued'] == TRUE) { 
            //echo $id . "Action if true";
        } else {
            changeDiscontinued($dbh, $id, $idDiscontinuedArray);
            //echo $id . "Items already discontinued!";
            }       
    }
    catch (PDOException $e) {
    echo $e->getMessage();
    }
}

Upvotes: 0

Views: 70

Answers (1)

newfurniturey
newfurniturey

Reputation: 38416

If you're looking to have the values in $rows, the result of $pdo->fetch(), to be numerically indexed, you can set the fetch style in the parameters to PDO::FETCH_NUM instead of PDO::FETCH_ASSOC:

$rows = $stmt->fetch(PDO::FETCH_NUM);

However, if you're looking for a "full array" of all records, you can switch to fetchAll() instead of pulling in a single result as with fetch():

$rows = $stmt->fetchAll(PDO::FETCH_NUM);

Upvotes: 2

Related Questions