問題描述
我想將特定數(shù)據(jù)庫的內(nèi)容存儲(chǔ)到按主鍵分組的數(shù)組中.(而不是 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).
我當(dāng)前的代碼:
$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
,但是我很快就會(huì)擴(kuò)展我希望能夠在此腳本上使用的數(shù)據(jù)量.這目前有效,但是當(dāng)我開始擴(kuò)大下載量并且更多客戶端開始使用時(shí),顯然數(shù)據(jù)的分組方式會(huì)導(dǎo)致問題.
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)對(duì)每個(gè)數(shù)組進(jìn)行分組嗎?
Is it possible for me to group each array by their primary key (which is id)?
推薦答案
我決定用 fetch() 循環(huán)遍歷結(jié)果,然后將它們輸入到一個(gè)數(shù)組中,這是我使用過的代碼并且它有效就好了:
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)作為數(shù)組鍵的名稱,然后將數(shù)據(jù)添加到其中.
Which uses the primary key (being id) as the name for the array key, and then adds the data into it.
我想我會(huì)添加這個(gè)作為答案,因?yàn)檫@解決了它,感謝提供幫助的人,我希望這對(duì)希望實(shí)現(xiàn)相同目標(biāo)的其他人有所幫助.
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.
這篇關(guān)于PDO fetchAll() 主鍵作為數(shù)組組鍵的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!