简体   繁体   English

为什么在PostgreSQL上的查询(在PHP上)返回字符串数组而不是assoc数组?

[英]Why a query on PostgreSQL (on PHP) return an array of strings instead of an assoc array?

This is a very common operation but I do not know why I have an array of string back. 这是一个非常常见的操作,但是我不知道为什么要返回一个字符串数组。

$res=$queryHelper->ExecuteQuery("
        SELECT (food.id,stores.name) 
        FROM food, stores 
        WHERE food.id_stores=stores.id");

QueryHelper Class QueryHelper类

    public function ExecuteQuery($queryRec,$executeRec=array())
    {
        $sql = $this->db->prepare($queryRec);
        $sql->execute($executeRec);
        $this->res=$sql->fetchAll();
        return $this->res;
    }  

TABLE FOOD 餐桌食物

id| name  | id_stores  
0 | PASTA | 0  
1 | FISH  | 0

TABLE STORES 表存储

id  |name  
0   | MARKET0  
1   | MARKET1  

$res is $ res是

Array ( [0] => Array ( [row] => (0,MARKET0) ) [1] => Array ( [row] => (1,MARKET0) ) )  

but I expect 但我希望

Array ( [0] => Array ( [0] => (0), [1] => ["MARKET0"] ) [1] => Array ([0] => (1), [1] => ["MARKET0"] ) )  

or something like this. 或类似的东西。
If there is only one table in the query all is fine. 如果查询中只有一个表,则一切正常。

The parentheses in your SELECT: SELECT中的括号:

SELECT (food.id,stores.name) 

are actually constructing a ROW type so the rows that come out of your query each have a single column which contains a ROW with two values. 实际上是在构造ROW类型,因此查询的每一行都有一个单独的列,其中包含带有两个值的ROW。 You can think of your query producing an array of rows and you're getting something that looks like this: 您可以想到您的查询产生了一个行数组,并且您得到的东西看起来像这样:

[
    [ [ food.id, stores.name ] ],
    ...
]

when you're expecting: 当您期望:

[
    [ food.id, stores.name ],
    ...
]

The solution is to toss out the parentheses: 解决方案是扔掉括号:

SELECT food.id,stores.name
FROM food, stores 
WHERE food.id_stores=stores.id

This behavior might be a little strange but it is documented : 此行为可能有点奇怪,但已记录在案

4.2.13. 4.2.13。 Row Constructors 行构造器

A row constructor is an expression that builds a row value (also called a composite value) using values for its member fields. 行构造函数是一个表达式,它使用其成员字段的值来构建行值(也称为复合值)。 A row constructor consists of the key word ROW , a left parenthesis, zero or more expressions (separated by commas) for the row field values, and finally a right parenthesis. 行构造函数由关键字ROW ,左括号,行字段值的零个或多个表达式(用逗号分隔)以及最后一个右括号组成。 For example: 例如:

 SELECT ROW(1,2.5,'this is a test'); 

The key word ROW is optional when there is more than one expression in the list. 当列表中有多个表达式时,关键字ROW是可选的。

Emphasis mine. 强调我的。 You have two expressions in your list so (food.id, stores.name) and food.id, stores.name are different things even though (food.id) and food.id are equivalent (but row(food.id) would be different). 您的列表中有两个表达式,因此(food.id, stores.name)即使(food.id)food.id是等效的,但(food.id, stores.name)food.id, stores.name是不同的东西(但row(food.id)会会有所不同)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM