Postgresql query result PHP encode converted array to string - php

I have an SQL query that converts result to 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 ;
I am using this query in PHP script.
$result = pg_query($connection, $queryString);
$resultArray = pg_fetch_all($result);
echo json_encode($resultArray[0]);
My php result is like this: (array is double-quote )
{
type: "FeatureCollection",
features: "[]"
}
But it should be like this:
{
type: "FeatureCollection",
features: []
}

It's important to remember that JSON is a way of representing data inside a string. PHP does not know that something is JSON, only that it's a string.
You need to first decode the result from Postgres (which is a JSON string) so that you have a PHP array. Then you can encode that PHP array back to 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]}'

Related

Add json object to json data fetched from database in php

In database JSON data is stored in below way:
{"name":"abc","score":5}
Now everytime I want to add json object with different name and score to same json data as :
{"name":"abc","score":5},{"name":"efg","score":8},{"name":"xyz","score":6}
Right now I have tried this code
$database_data = $row['JSONstring']; //fetched json string from database
$json_decode_data = json_decode($database);
array_push($json_decode_data, $new_json_string); //data to append to database data
$updated_json_data = json_encode($json_decode_data); // at last encode the update json data
But this don't work and throws a warning : Parameter 1 is an object.
How do solve it ?
Now with all the answer and comments given here I got the required answer. So I appreciate all your help.
In my question starting, the first JSON String format is invalid:
{"name":"abc","score":5}
Instead of this, it would be :
[{"name":"abc","score":5}]
Required JSON data's format would be:
[{"name":"abc","score":5},{"name":"efg","score":8},{"name":"xyz","score":6}]
And this is achieved by array_merge() function as follows:
Code to append json object to json object string
//fetched json string from database
ie.[{"name":"abc","score":5}]
$database_data = $row['JSONstring'];
//decode both string the database data string and the new one which is to be merged
$json_decode_database_data = json_decode($database_data, true);
$json_decode_new_data = json_decode($database_data, true);
//merge both the decoded array by array_merge()
$required_json_data = array_merge($json_decode_data, $new_json_string);
//at last encode required json data
$updated_json_data = json_encode($required_json_data);
// You will get required json data
[{"name":"abc","score":5},{"name":"efg","score":8},{"name":"xyz","score":6}]

Group Database data encoded as JSON using PHP

Is there anyway to format JSON encoded data that is fetched from
mysql Database , with an index ?
Example :
The current JSON i have in text :
[{"category_id":"1","category_name":"Luarb1"},{"category_id":"2","category_name":"Luarb2"}]
How i want it to be formatted :
{"1":[{"category_id":"1","category_name":"Luarb1"}], "2":[{"category_id":"2","category_name":"Luarb2"}]}
<?php
// init variables
$arr = '[{"category_id":"1","category_name":"Luarb1"},{"category_id":"2","category_name":"Luarb2"}]';
$new = [];
// decode JSON array
$decoded = json_decode($arr);
// create the new array to be encoded
$i = 1;
foreach ($decoded as $cur) {
$new[$i++] = [$cur];
}
// encode the new array
$encoded = json_encode($new);
// test if everything worked
var_dump($encoded);
// tests.php:15:string '{"1":[{"category_id":"1","category_name":"Luarb1"}],"2":[{"category_id":"2","category_name":"Luarb2"}]}' (length=103)
Here is how I solved your problem, I didn't succeed in starting the array key at 0 but you wanted to be at 1 I think).
If you want the index from the database entry, you may need to improve your SELECT SQL query and retrieve id, then parse it in JSON and so on...

Convert JSON string from database to PHP array problems

I am trying to convert this JSON string into a PHP array. The JSON string is stored in my database and I have already retrieved it.
{
"users": "user1, user2"
}
I need to convert the above JSON string into an array like the following but dynamically.
$myArray = array("user1", "user2")
This is my code:
$row = mysqli_fetch_array($result);
$json = $row['json'];
$decode = json_decode($json);
$list = $decode->users;
$myArray = explode(',', $list);
This code doesn't work in my program but when I print the array with print_r it looks identical to if I print $myArray from the nondynamic string. This is a concern because the nondynamic string works.
The separator between the usernames is comma+space, you're just using comma when you explode, so the second and following usernames are getting a space at the beginning. Try:
$myArray = explode(', ', $list);
I recommend that you change the JSON structure so you store an actual array, rather than a comma-separated list.
{
"users": ["user1", "user2"]
}
Even better would be to change your database structure so the users are in a real table, rather than being wrapped in JSON. This would allow you to perform queries that search for users easily and efficiently.

Query and decode json form mysql database

I have this JSON encoded code in my mysql database:
{"Suggestion":{"Title":"Casinos","Text":"maybe it will be good if its there casinos "},"ID":6,"VoteNo":[],"Status":"Voting","Player":{"SteamID":"STEAM_0:1:36988062","Name":"Pepi"},"Approved":{"Name":"Nido Johnson","Is":true,"SteamID":"STEAM_0:0:47457253"},"VoteYes":{"1":"STEAM_0:0:56939043","2":"STEAM_0:0:55948188","3":"STEAM_0:1:25856984","4":"STEAM_0:1:40894071"}}
And i want to query and decode it to echo it at my website.
You have to use a php "json_decode()" function to decode a json encoded data.
Basically json_decode() function converts JSON data to a PHP array.
Syntax: json_decode( data, dataTypeBoolean, depth, options )
data : - The json data that you want to decode in PHP.
dataTypeBoolean(Optional) :- boolean that makes the function return a PHP Associative Array if set to "true", or return a PHP stdClass object if you omit this parameter or set it to "false". Both data types can be accessed like an array and use array based PHP loops for parsing.
depth :- Optional recursion limit. Use an integer as the value for this parameter.
options :- Optional JSON_BIGINT_AS_STRING parameter.
Now Comes to your Code
$json_string = '{"Suggestion":{"Title":"Casinos","Text":"maybe it will be good if its there casinos "},"ID":6,"VoteNo":[],"Status":"Voting","Player":{"SteamID":"STEAM_0:1:36988062","Name":"Pepi"},"Approved":{"Name":"Nido Johnson","Is":true,"SteamID":"STEAM_0:0:47457253"},"VoteYes":{"1":"STEAM_0:0:56939043","2":"STEAM_0:0:55948188","3":"STEAM_0:1:25856984","4":"STEAM_0:1:40894071"}}';
Assign a valid json data to a variable $json_string within single quot's ('') as
json string already have double quots.
// here i am decoding a json string by using a php 'json_decode' function, as mentioned above & passing a true parameter to get a PHP associative array otherwise it will bydefault return a PHP std class objecy array.
/ just can check here your encoded array data.
// echo '<pre>';
// print_r($json_decoded_data);
// loop to extract data from an array
foreach ($json_decoded_data as $key => $value) {
echo "$key <br/>";
foreach($value as $k=>$data)
{
echo "$k | $data <br/>";
}
}

Get the value for key in json array in php

How to get the corresponding value for key associated
[{"name":"challenge","properties":[{"name":"mobileNo","value":"aa"},{"name":"challengeT","value":"1Day"},{"name":"emailId","value":"ff#gmail.com"},{"name":"deviceId","value":"9500e297-081b-4f97-93b7-dafddc55db31"}]},{"name":"challenge","properties":[{"name":"emailId","value":"a#b.com"},{"name":"mobileNo","value":"345345"},{"name":"deviceId","value":"435435dfgdfg"}]}]
Your Json is valid. You can validate at following
website: http://jsonlint.com/
You have to use a php "json_decode()" function to decode a json encoded data.
Basically json_decode() function converts JSON data to a PHP array.
Syntax: json_decode( data, dataTypeBoolean, depth, options )
data : - The json data that you want to decode in PHP.
dataTypeBoolean(Optional) :- boolean that makes the function return a PHP Associative Array if set to "true", or return a PHP stdClass object if you omit this parameter or set it to "false". Both data types can be accessed like an array and use array based PHP loops for parsing.
depth :- Optional recursion limit. Use an integer as the value for this parameter.
options :- Optional JSON_BIGINT_AS_STRING parameter.
Now Comes to your Code
$json_string = '[{"name":"challenge","properties":[{"name":"mobileNo","value":"aa"},{"name":"challengeT","value":"1Day"},{"name":"emailId","value":"ff#gmail.com"},{"name":"deviceId","value":"9500e297-081b-4f97-93b7-dafddc55db31"}]},{"name":"challenge","properties":[{"name":"emailId","value":"a#b.com"},{"name":"mobileNo","value":"345345"},{"name":"deviceId","value":"435435dfgdfg"}]}]' ;
Assign a valid json data to a variable $json_string within single quot's ('') as
json string already have double quots.
// here i am decoding a json string by using a php 'json_decode' function, as mentioned above & passing a true parameter to get a PHP associative array otherwise it will bydefault return a PHP std class objecy array.
$json_decoded_data = json_decode($json_string, true);
// just can check here your encoded array data.
// echo '<pre>';
// print_r($json_decoded_data);
// loop to extract data from an array
foreach ($json_decoded_data as $key => $value) {
echo "$key <br/>";
foreach ($value as $key2 => $value2) {
echo "$key2 = $value2 <br />";
}
}
Output :
0
name = challenge
properties = Array
1
name = challenge
properties = Array

Categories