gpt4 book ai didi

php - Postgresql查询结果PHP编码转换数组为字符串

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

我有一个将结果转换为 json 的 SQL 查询。

SELECT 'FeatureCollection' As type, array_to_json(array_agg(f)) As features FROM (
SELECT 'Feature' As type,
ST_AsGeoJSON(geom)::json As geometry,
row_to_json((name, category)) As properties
FROM my_geometry_table
) As f ;

我在 PHP 脚本中使用这个查询。

$result = pg_query($connection, $queryString);
$resultArray = pg_fetch_all($result);

echo json_encode($resultArray[0]);

我的 php 结果是这样的:(数组是双引号)

{
type: "FeatureCollection",
features: "[]"
}

但是应该是这样的:

{
type: "FeatureCollection",
features: []
}

最佳答案

请务必记住,JSON 是一种在字符串中表示数据的方式。 PHP 不知道某些东西是 JSON,只知道它是一个字符串。

您需要先解码 来自 Postgres 的结果(这是一个 JSON 字符串),以便您拥有一个 PHP 数组。然后您可以将 PHP 数组编码回 JSON:

$result = pg_query($connection, $queryString);
$resultArray = pg_fetch_all($result);
// $resultArray[0]['features'] is a string of JSON data from the DB
// For example, let's say it's '[1,2,3]'

// To you, this is obviously JSON: it looks like it,
// and you know you asked for that column to be JSON in the SQL.
// But PHP has no idea; it just sees a 7-character long string;
// so we need to tell it to decode that string:
$decoded_features_array = json_decode($resultArray[0]['features']);
// $decoded_features_array is now a PHP array containing 1, 2, and 3

// Obviously, you can just write that value straight back into the result
$resultArray[0]['features'] = json_decode($resultArray[0]['features']);

// Now the 'features' field of the result is an actual array,
// not a string, so we can do with it whatever we'd do with any other array

// That includes encoding it to send somewhere else - in this case, as JSON:
$json_result = json_encode($resultArray[0]);
// $json_result is now a string with all the fields
// and our PHP array gets encoded as a JSON array as we wanted:
// e.g. '{"type": "FeatureCollection", "features": [1,2,3]}'

关于php - Postgresql查询结果PHP编码转换数组为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35204456/

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