php - 从 postgres 中检索数组

标签 php arrays postgresql pdo

非常基本的问题,但找不到解决方案。

在一个包含一些值的表中,我尝试在 1 列中存储一个数组 (int[]) 并检索它。存储和搜索工作正常,但如果我选择它,我会在 php 中将其作为字符串获取。

表周

col id (int) = 1
col days (int[]) = {1,1,1,1,1,0,0}

PHP

$query = SELECT id, days, manyother FROM week //array_to_json(days) does the same result
$pdo->setAttribute( PDO::ATTR_CASE, PDO::CASE_NATURAL );
$result = $pdo->query($query);

$test = $result->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($test)

返回:

id: 1
days: "[1,1,1,1,1,0,0]"
manyother: ""

我确定我错过了一些关于 json_encode/decode 的东西 编辑:它不受 json_encode 的影响,我调试了它并在它返回类似“[1,1,1,1,1,0,0]”的值之前。

编辑 2:找到了一个有效但加载时间增加 15* 倍的解决方案 :D 所以问题仍然悬而未决,但我目前有一个解决方法。

foreach($test as $key => $value){
        $test[$key]['days'] = json_decode($value['days']);
}

最佳答案

选择数组时,你可以修改数组的显示方式:

t=# select json_build_array(array[1,2,3,4])->0;
 ?column?
-----------
 [1,2,3,4]
(1 row)

它应该很容易被 php 然后用 eval 求值。或者甚至在整个数据集上使用 json_agg 然后进行评估:

t=# select json_agg(s162) from s162;
json_agg
[{"i":0,"a":[1,2,3,4]},
 {"i":1,"a":[1,4]}]
(1 row)
Time: 0.281 ms

关于php - 从 postgres 中检索数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44066775/

相关文章:

php - codeigniter 删除 index.php 表单 url

php - PDOStatement::execute(): SQLSTATE[HY093]: 参数号无效:参数未定义

PHP stream_get_contents() 从数据库读取 LOB 时表现异常

ruby 数组检查 nil 数组

SQL Upsert 语句不适用于非索引列

postgresql - Postgres : update specific json object in array

python - 通过 python 将表名作为 postgres 中的参数传递

php - 调用具有多个变量的函数

c++ - 'sort(int [2000], int)' 没有匹配函数 |排序数组时

ios - 从值是字典数组的字典中获取值