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

查看:75
本文介绍了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天全站免登陆