PDO fetchAll() 主键作为数组组键 [英] PDO fetchAll() primary key as array group key

查看:16
本文介绍了PDO fetchAll() 主键作为数组组键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将特定数据库的内容存储到按主键分组的数组中.(而不是 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() 主键作为数组组键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆