Group Database data encoded as JSON using PHP - 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...

Related

Turn json file into php array to select random name from the array

Problem is as follows:
I'm exporting a list of names and values(repCode) attached to each name from excel into a json file.
I then want to convert the json file into a php array so that I can have a piece of code that will select a random name from the php array and display the random name(and value(repCode) attached to the name).
I've tried many options so far but I keep running into problems that I'm struggling to find a solution for. One example would be:
<?php
$jsondata = file_get_contents("Names.json");
$json = json_decode($jsondata, true);
$output = '<ul>';
foreach($json['Reps']as $reps){
$output .='<h4>' .$reps['Client']."<h4>";
$output .= "<li>".$reps['Code']."</li>";
}
$output .= "</ul>";
$element = $output[mt_rand(0, count($output) - 1)];
echo $element;
?>
That doesn't work.
json File as follow: "Names.json"
{
"Reps": [
{"Client":"Jack",
"repCode":"tt1790861"},
{"Client":"James",
"repCode":"tt1790862"},
{"Client":"Sam",
"repCode":"tt1790863"},
{"Client":"Hendry",
"repCode":"tt1790864"},
{"Client":"Samone",
"repCode":"tt1790865"},
{"Client":"Judy",
"repCode":"tt179086"},
{"Client":"Jake",
"repCode":"tt1790867"},
{"Client":"Amy",
"repCode":"tt1790868"},
{"Client":"Brandon",
"repCode":"tt1790869"},
{"Client":"Blake",
"repCode":"tt17908610"},
{"Client":"Rick",
"repCode":"tt17908611"},
{"Client":"Morty",
"repCode":"tt17908612"}
]
}
And then below is some php code:
<?php
// JSON string
$someJSON = "Names.json";
// Convert JSON string to Array
$someArray = json_decode($someJSON, true);
print_r($someArray); // Dump all data of the Array
echo $someArray[0]["Client"]; // Access Array data
?>
I'm getting no result when I echo out the json file.
So I can't even get to the part where I want to use the json file that's been converted into a php array so I can have code to select a random name + associated rep code and display it.
Any help would be appreciated.
In your first example you're trying to use $output as an array, it's not. Also, you're not accessing the keys of $element:
$element = $json['Reps'][mt_rand(0, count($json['Reps']) - 1)];
//or
$element = $json['Reps'][array_rand($json['Reps'])];
echo $element['Client'];
echo $element['repCode'];
For your second example, you're not actually loading the JSON file and then you forget the Reps key:
$someJSON = file_get_contents("Names.json");
$someArray = json_decode($someJSON, true);
print_r($someArray);
echo $someArray["Reps"][0]["Client"];
//or random
echo $someArray["Reps"][array_rand($someArray["Reps"])]["Client"];

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}]

json_decode returning NULL [{},{}]

I'm pulling information from our database (entered with GLua) with PHP, then using json_decode to change it to an array to work with but it's returning NULL, whereas other ones are working?
// Get the RapSheet info from 'character_data_store'
$rap = mysql_query("SELECT * FROM `character_data_store` WHERE `character_id` = '$srp_uid' AND `key`='RapSheet'");
while($rapsheet=mysql_fetch_assoc($rap)){
$raps = $rapsheet['value'];
};
Then I use
// Deal with the rapsheet JSON
echo $raps;
$raps = json_decode($rapsheet, true);
echo var_dump($raps, TRUE);
The echo's are to check that it's working, the information is being pulled successfully as it echos, although the var_dump returns
NULL bool(true)
Database contents:
[{"ArrestedBy":"James Scott","Date":1483732483,"Duration":60,"LeaveReason":"Jail time served.","ArrestReason":"test"}]
Any help will be appreciated!
After trying Darren's response:
I tried
$rap = mysql_query("SELECT * FROM `character_data_store` WHERE `character_id` = '$srp_uid' AND `key`='RapSheet'");
$raps = array();
while($rapsheet=mysql_fetch_assoc($rap)){
$raps[] = $rapsheet['value'];
};
// encode
$rap = json_encode($raps, TRUE);
echo $rap;
And that returned:
["[{\"ArrestedBy\":\"James Scott\",\"Date\":1483732483,\"Duration\":60,\"LeaveReason\":\"Jail time served.\",\"ArrestReason\":\"test\"}]"]
So I tried
echo $rap['ArrestedBy'];
and it returned
[
You're trying to access variables that aren't within the proper scope. $rapsheet is only ever accessible within your while() {... loop as it will be that current row of data. What you want to do is create $raps as an array and insert the lines within it. From there you'll be able to json_decode() as you please. Depending on how many rows you've got, you may need to loop over $raps and decode each array element.
$raps = array();
while($rapsheet=mysql_fetch_assoc($rap)){
$raps[] = $rapsheet['value'];
};
// encode
$rap = json_encode($raps, TRUE);

Postgresql query result PHP encode converted array to string

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

How to insert json array into mysql database with php

Hi I'm trying to insert the json array into my MySQL database.With array json data from android client.
[{"name":"peter","phone":"dsf","city":"sdfsdf","email":"dsf"},{"name":"111","phone":"222","city":"hn","email":"1#yahoo.com"}]
If you want to store the array as a string, you can use JSON.stringify():
$string = [{"name":"peter","phone":"dsf","city":"sdfsdf","email":"dsf"},{"name":"111","phone":"222","city":"hn","email":"1#yahoo.com"}];
$json = JSON.stringify($string);
The variable $json is then a simple string which can be inserted into MySQL easily.
You can then use:
var obj = JSON.parse($json);
To convert the string back to an array.
This method usually isn't recommended for performance reasons though, so you might alternatively want to break up the array and store each field individually.
Try this:
$json = serialize(json_array);
Use $jsonArray = json_decode($jsonStr);.
Then iterate the array as you want to save data in your mysql database.
you can use - serialize()
$json = '[{"name":"peter","phone":"dsf","city":"sdfsdf","email":"dsf"},{"name":"111","phone":"222","city":"hn","email":"1#yahoo.com"}]';
$newJson = serialize(json_decode($json));
$newJson is ready to be inserted. and after fetching -
$data = unserialize($fetchedData); and then json_encode($data);

Categories