PDO fetchAll() primary key as array group key

后端 未结 6 898
南笙
南笙 2020-12-10 04:26

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 curr

6条回答
  •  不知归路
    2020-12-10 04:56

    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.

提交回复
热议问题