PDO获取数组数组.外部具有数字索引.内在联想指数 [英] PDO fetch array of arrays. Outer has numeric index. Inner has associative index
问题描述
Am正在处理学生课程和答案的数据库.每个作业和每个结果都有一个关联数组,该数组具有六个或更多字段(列),这些字段存储在MySQL数据库中的课程表和答案表中.
Am working on a database of student lessons and answers. Each assignment and each result has an associative array with six or more fields (columns) stored in a MySQL database in lesson and answer tables.
我使用sql PDO execute()获取所有分配,还使用不同的sql获取所有结果.
I use sql PDO execute() to get all the assignments and also different sql to get all the results.
FetchAll为我提供了一个外部数字数组和一个具有数字索引和关联索引的内部数组.我只想要内部数组上的关联索引. ->fetch(\PDO::FETCH_ASSOC);
什么也没给我. (由于命名空间而导致\ -没有\,我得到一个错误)->fetchAll();
给了我一个外部数字索引数组和两个索引的内部数组.
FetchAll gives me an outer numeric array and an inner array with both numeric and associative indexes. I want only associative indexes on the inner array. ->fetch(\PDO::FETCH_ASSOC);
gives me nothing. (the \ due to name spaces -- without the \ I get an error) ->fetchAll();
gives me an outer numeric index array and the inner arrays with both indexes.
我可以删除内部数字索引或忽略它们,但是由于这些内部数组的使用方式很多,所以似乎很笨拙.
I can strip out the inner numeric indexes or ignore them, but that seems klutzy as these inner arrays are used many ways.
也许答案是在sql中而不是在fetch中.到目前为止,我能想到的最好的方法是剥离数字索引:
Perhaps the answer is in the sql instead of the fetch. The best I have come up with so far is stripping out the numeric indexes with:
$stmt->execute();
$rows = $stmt->fetchAll();
foreach ($rows as $key=>$value) {
foreach ($value as $key2=>$value2) {
if (is_numeric($key2) === TRUE) {
unset($value[$key2]);
}
}
$rows[$key] = $value;
}
return $rows;
有更好的方法吗?
吉姆富夸
推荐答案
在迈克尔·伯可夫斯基(Michael Berkowski)的评论的帮助下,我尝试了一个实验.
With help from Michael Berkowski's comment, I tried an experiment.
使用$ rows = $ stmt-> fetchAll(\ PDO :: FETCH_ASSOC);我得到了我想要的东西.外部数组具有数字索引,内部数组具有关联索引.
With $rows = $stmt->fetchAll(\PDO::FETCH_ASSOC); I got just what I was looking for. The outer array had a numeric index and the inner array had an associative index.
使用$ rows = $ stmt-> fetchAll();我得到了我想要避免的重复.
With $rows = $stmt->fetchAll(); I got the duplication I was trying to avoid.
使用$ rows = $ stmt-> fetch(\ PDO :: FETCH_ASSOC);我只有一个内部数组关联.没有外部阵列,内部阵列之一缺失.因为它们是相同的,所以我无法确定哪个内部数组丢失了.
With $rows = $stmt->fetch(\PDO::FETCH_ASSOC); I got one of the inner arrays as associative only. There was no outer array and one of the inner arrays was missing. Because they were identical, I could not tell which inner array was lost.
JimFuqua
这篇关于PDO获取数组数组.外部具有数字索引.内在联想指数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!