Postgresql查询结果PHP将转换后的数组编码为字符串

时间:2016-02-04 15:02:40

标签: php json postgresql postgis

我有一个将结果转换为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: []
}

1 个答案:

答案 0 :(得分:1)

记住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]}'