Результат запроса Postgresql PHP кодирует преобразованный массив в строку

1

У меня есть SQL-запрос, который преобразует результат в json.

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: []
}
Теги:
postgis

1 ответ

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 say it '[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]}'
  • 0
    Но $ db_result ['foo'] содержит несколько массивов. Как я могу узнать, что такое массив?
  • 0
    Мой пример был немного поспешным; Я отредактировал его, чтобы более точно соответствовать примеру в вашем вопросе, и добавил больше комментариев, чтобы объяснить, что происходит. Это имеет больше смысла, или есть что-то еще неясно?

Ещё вопросы

Сообщество Overcoder
Наверх
Меню