PDO fetchAll() primary key as array group key

This should yield what you are looking for :

$results = $pdos->fetchAll(\PDO::FETCH_UNIQUE|\PDO::FETCH_ASSOC);

You can just use

$results = array_map('reset', $stmt->fetchAll(PDO::FETCH_GROUP|PDO::FETCH_ASSOC))

PDO::FETCH_GROUP|PDO::FETCH_ASSOC returns an array of arrays. The first column is used as the key, and then within key is an array of all the results for that key. However, in our scenario each key will only contain 1 row. reset() returns the first element in array, thus eliminating 1 level of nesting.


I decided to just loop through the results with fetch() and enter them into an array as I go along, this is the code I have used and it works just fine:

$DownloadsPDO = $database->dbh->query("SELECT * FROM `downloads`");
$Array = array();
while ($d = $DownloadsPDO->fetch()) {
    $Array[$d['id']]["id"] = $d['id'];
    $Array[$d['id']]["name"] = $d['name'];
    $Array[$d['id']]["path"] = $d['path'];                          
}

// Outputs
Array ( [1] => Array ( [id] => 1 [name] => Test Script [path] => /xxxx/testfile.zip ) [2] => Array ( [id] => 2 [name] => New Script-UPDATE [path] => /xxxx/testfile.zip ) ) 

Which uses the primary key (being id) as the name for the array key, and then adds the data into it.

Thought I would add this as the answer as this solved it, thanks to the guys that helped out and I hope this is helpful to anyone else hoping to achieve the same thing.

Tags:

Php

Pdo