Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PDO fetchAll() primary key as array group key

Tags:

php

pdo

I want to store the contents of a specific database into an array, grouped by their primary keys. (Instead of the useless way PDO fetchAll() organises them).

My current code:

$DownloadsPDO = $database->dbh->prepare("SELECT * FROM `downloads`");
$DownloadsArray =  $DownloadsPDO->execute();
$DownloadsArray =  $DownloadsPDO->fetchAll();

Which then outputs:

Array ( [0] => Array ( [id] => 0 [0] => 0 [path] => /xx-xx/testfile.zip [1] => /xx-xx/testfile.zip [name] => Test Script [2] => Test Script [status] => 1 [3] => 1 ) [1] => Array ( [id] => 1 [0] => 1 [path] => /xx-xx/test--file.zip [1] => /xxxx/testfile.zip [name] => New Script-UPDATE [2] => New Script-UPDATE [status] => 1 [3] => 1 ) )

I was considering to use PDO::FETCH_PAIR, however I will be very soon expanding the amount of data I want to be able to use on this script. This works currently, but when I start to expand the amount of downloads and more clients come into play, obviously the way the data is grouped causes an issue.

Is it possible for me to group each array by their primary key (which is id)?

like image 258
Jake Ball Avatar asked Apr 02 '13 01:04

Jake Ball


2 Answers

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.

like image 179
mpen Avatar answered Oct 18 '22 20:10

mpen


This should yield what you are looking for :

$results = $pdos->fetchAll(\PDO::FETCH_UNIQUE|\PDO::FETCH_ASSOC);
like image 32
Martin J. Avatar answered Oct 18 '22 21:10

Martin J.