gpt4 book ai didi

php - 为什么对 PostgreSQL(在 PHP 上)的查询返回一个字符串数组而不是一个关联数组?

转载 作者:行者123 更新时间:2023-11-29 13:28:00 24 4
gpt4 key购买 nike

这是一个很常见的操作,但我不知道为什么我返回的是一个字符串数组。

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

查询助手类

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

餐 table 上的食物

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

表店

id  |name  
0 | MARKET0
1 | MARKET1

$res 是

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

但我希望

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

或者类似这样的东西。
如果查询中只有一个表,则一切正常。

最佳答案

SELECT 中的括号:

SELECT (food.id,stores.name) 

实际上是在构造一个 ROW 类型,因此从您的查询中得出的每行都有一个列,其中包含一个具有两个值的 ROW。您可以认为您的查询生成了一个行数组,并且您得到的结果如下所示:

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

当你期待时:

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

解决方案是去掉括号:

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

这种行为可能有点奇怪,但它是 documented :

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. 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.

强调我的。您的列表中有两个表达式,所以 (food.id, stores.name)food.id, stores.name 是不同的东西,即使 (food. id)food.id 是等价的(但是 row(food.id) 会不同)。

关于php - 为什么对 PostgreSQL(在 PHP 上)的查询返回一个字符串数组而不是一个关联数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29995163/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com