PDO fetchAll () primary key as array group key

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

My current code is:

$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 going to use PDO::FETCH_PAIR, but very soon I will increase the amount of data that I want to use in this scenario. This currently works, but when I start to increase the number of downloads and more and more clients come into the game, obviously the way of grouping the data causes a problem.

Can I group each array by primary key (i.e. identifier)?

+9
source share
6 answers

fetch() , , , :

$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 ) ) 

( id), .

, , , , , , , .

+5

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

, :

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

, :

fetchAll(\PDO::FETCH_GROUP|\PDO::FETCH_UNIQUE|\PDO::FETCH_ASSOC);

, . , :

SELECT id_keyname AS arrkey, id_keyname, .... FROM ...

+3

fetch(). array_reduce() . .

( ) :

$myFinalArray = array_reduce($myInputArray, function($returnArray, $temp) { 
    $temp2 = $temp['id']; 
    unset($temp['id']); 
    $returnArray[$temp2] = $temp; 
    return $returnArray;
  }
);
+2

, : ( id)

, 2 : , . , , , .

: SQL, . , OKAY. get result-set, prepare() fetch() .

, :

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

:

Array( [id] => Array('bar' => 'foo') ....)

, - :

$stmt = $database->dbh->query("SELECT * FROM `downloads`");
$result = array();

foreach($stmt as $array){

  $result[$array['id']] = $array;
}


print_r($result); // Outputs: Array(Array('id' => Array(...)))
+1

All Articles