問題描述
我想將特定數據庫的內容存儲到按主鍵分組的數組中.(而不是 PDO fetchAll() 組織它們的無用方式).
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).
我當前的代碼:
$DownloadsPDO = $database->dbh->prepare("SELECT * FROM `downloads`");
$DownloadsArray = $DownloadsPDO->execute();
$DownloadsArray = $DownloadsPDO->fetchAll();
然后輸出:
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 ) )
我曾考慮使用 PDO::FETCH_PAIR
,但是我很快就會擴展我希望能夠在此腳本上使用的數據量.這目前有效,但是當我開始擴大下載量并且更多客戶端開始使用時,顯然數據的分組方式會導致問題.
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.
我可以按主鍵(即 id)對每個數組進行分組嗎?
Is it possible for me to group each array by their primary key (which is id)?
推薦答案
我決定用 fetch() 循環遍歷結果,然后將它們輸入到一個數組中,這是我使用過的代碼并且它有效就好了:
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 ) )
它使用主鍵(即id)作為數組鍵的名稱,然后將數據添加到其中.
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.
這篇關于PDO fetchAll() 主鍵作為數組組鍵的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!