I have accessed this json file on my website:
[{
"01:03:2016": "410",
"02:03:2016": "200",
"03:03:2016": "380"
}]
I want to use PHP to change the formatting to something like this, where the dates and counts are all values:
[{
"date": "01:03:2016",
"count": "410"
},
{
"date": "02:03:2016",
"count": "200"
},
{
"date": "03:03:2016",
"count": "380"
}]
PHP
$string = file_get_contents("data.json"); // your current json data
$json_a = json_decode($string, true);
$new_json = array();
foreach ($json_a as $key => $value) {
$new_json[] = array("date"=>$key,'count'=>$value);
}
echo json_encode($new_json); //output
data.json file (your current data)
[{
"01:03:2016": "410",
"02:03:2016": "200",
"03:03:2016": "380"
}]
Related
I have multiple JSON files with different structures. What I want to do is to automatically display these JSON outputs with HTML.
Some of my JSON outputs are as follows: (Think of each of these as separate files and need to be processed separately)
{
"parts": [
{
"#attributes": {
"id": "part1"
},
"car": "Peugeot",
"service": 5,
"location": 2996,
"price": "44.95",
"date": "2000-10-01"
},
... other objects
]
}
{
"licenses":[
{
"driver":"John",
"year":26,
"info":null
},
... other objects
]
}
Now, to process these files, I send the page name with GET on PHP and I want the corresponding JSON output to be printed to the screen with HTML as <span>$key</span> -> <span>$value</span>
How can I make this dynamic JSON output read event with PHP? Do I need to create a recursive function?
Because the files have different structures from each other. I hope I was able to explain my problem. Thanks already for yours help.
I suggest the following:
get required JSON file name from GET or POST, for example:
$jsonfilename = $_GET['file'];
The above does not include any security protection! this is a separate topic,
so do some research.
load your json file and parse it:
$json = file_get_contents('/path/'.$jsonfilename);
$data = json_decode($json, true);
read your json data:
foreach ($data as $key=>$value){
echo ''.$key.' -> '.$value.'';
}
A simple example for your PARTS file:
$json = '
{
"parts":
[
{
"#attributes": {
"id": "part1"
},
"car": "Peugeot",
"service": 5,
"location": 2996,
"price": "44.95",
"date": "2000-10-01"
},
{
"#attributes": {
"id": "part2"
},
"car": "Renault",
"service": 8,
"location": 3100,
"price": "99.95",
"date": "2022-03-01"
}
]
}';
$arr = json_decode($json, true);
foreach($arr["parts"] as $part) {
foreach($part as $k => $v){
if($k == "#attributes")
echo "<h1>" . $v["id"] ."</h1>";
else
echo "<span>$k</span> -> <span>$v</span> <br/>";
}
}
This produces:
i have a json file structured this way:
{
"data": {
"Category": {
"Product1": [{
"Code": "abc"
}],
"Product2": [{
"Code": "cba"
}]
},
"Category2": {
"Product3": [{
"Code": "abcabc"
}],
"Product4": [{
"Code": "cbacba"
}]
},
"Category3": {
"Product5": [{
"Code": "abcabcabc"
}],
"Product6": [{
"Code": "cbacbacba"
}]
}
}
}
How can i change the category names with a php script?
for example if i have 2 variables received from a form, called "$oldcategory" (which will be one of the existing categories) and "$newcategory" how can it, open the json file, place "$newcategory" where "$oldcategory" is and re-save the file?
<?php
$oldcategory= $_POST['oldcategory'];
$newcategory= $_POST['newcategory'];
$jsonString = file_get_contents('data.json');
$data = json_decode($jsonString, true);
...
foreach($data["data"] as $key=>$value){
$new = $data["data"][$oldcategory];
$data["data"][$newcategory]= $new ;
}
unset($data["data"][$oldcategory]);
$newJsonString = json_encode($data);
file_put_contents('data.json', $newJsonString);
?>
in case i was changing the "Category2" i'd like the result to be:
{
"data": {
"Category": {
"Product1": [{
"Code": "abc"
}],
"Product2": [{
"Code": "cba"
}]
},
"New_Category2": {
"Product3": [{
"Code": "abcabc"
}],
"Product4": [{
"Code": "cbacba"
}]
},
"Category3": {
"Product5": [{
"Code": "abcabcabc"
}],
"Product6": [{
"Code": "cbacbacba"
}]
}
}
}
instead of this:
{
"data": {
"Category": {
"Product1": [{
"Code": "abc"
}],
"Product2": [{
"Code": "cba"
}]
},
"Category3": {
"Product5": [{
"Code": "abcabcabc"
}],
"Product6": [{
"Code": "cbacbacba"
}]
},
"New_Category2": {
"Product3": [{
"Code": "abcabc"
}],
"Product4": [{
"Code": "cbacba"
}]
}
}
}
This was a possible solution:
foreach($data["data"] as $key=>$value){
if ($key == $oldcategory){
$key = $newcategory;}
$new["data"][$key] = $value;
}
$newJsonString = json_encode($new);
file_put_contents('data.json', $newJsonString);
This ended up being the solution to my problem:
<?php
$oldcategory= $_POST['oldcategory'];
$newcategory= $_POST['newcategory'];
$jsonString = file_get_contents('data.json');
$data = json_decode($jsonString, true);
...
foreach($data["data"] as $key=>$value){
if ($key == $oldcategory){
$key = $newcategory;}
$new["data"][$key] = $value;
}
$newJsonString = json_encode($new);
file_put_contents('data.json', $newJsonString);
?>
You could use a conditional, and create a new array with the desired values. When you reach the $oldcategory in your loop, replace the key with the $newcategory.
$newArray = [];
foreach($data["data"] as $key=>$value){
if($key == $oldcategory) {
$newArray[$newcategory] = $value;
} else {
$newArray[$key] = $value;
}
}
$newJsonString = json_encode($newArray);
I'm trying to get JSON by name and save it as a variable with everything related to that nest,
what would the best way to accomplish this?
(in my scenario the names are unique)
[{
"name": "Joe",
"age": "30",
"gender": "male"
},
{
"name": "Logan",
"age": "27",
"gender": "male"
}]
to something like this
{
"Joe": [{
"name": "Joe",
"age": "30",
"gender": "male"
}],
"Logan": [{
"name": "Logan",
"age": "27",
"gender": "male"
}]
}
i need to be able to search on the name to get the correct one, the API switches order so can't get it from just id
Hi This might helps you
$list = '[
{
"name":"Joe",
"age":"30",
"gender":"male"
},
{
"name":"Logan",
"age":"27",
"gender":"male"
}]';
$newjson = json_decode($list, true);
$final = [];
foreach ($newjson as $key => $value) {
$final[$value['name']][]=$value;
}
$finaloutput = json_encode($final, true);
echo "<pre>";
print_r($finaloutput);
echo "</pre>";
exit;
The output is
{"Joe":
[{"name":"Joe","age":"30","gender":"male"}],
"Logan":
[{"name":"Logan","age":"27","gender":"male"}]}
The Laravel Collections Library is a very useful lib to use cases like yours.
For this problem you could use the keyBy method!
$json = '[
{
"name":"Joe",
"age":"30",
"gender":"male"
},
{
"name":"Logan",
"age":"27",
"gender":"male"
}
]';
$array = collect(json_decode($json, true))->keyBy('name')->all();
print_r($array); // will be the array with the keys defined by the name!
See https://laravel.com/docs/5.5/collections#method-keyby
I have a json file with a lot of records with fields for date, time and isApproved. What I am trying to do is to create a json rray that has dates for all the records that are approved. And the dates have all the hours that are booked for the current date.
So from this... :
[{"fullName":"Jojn Petkobsky","userName":"user1","phone":"12415455","email":"ees#asd.com"date":"11\/16\/2016","time":"1pm ","reason":"ReaReasonReaeason","isApproved":0,"label":"warning","status":"Approved"},{"fullName":"Zoltan Heinkelman","userName":"user2","phone":"12415455","email":"ees#asdd.com"date":"11\/16\/2016","time":"2pm ","reason":"ReaReasonReaeason","isApproved":1,"label":"warning","status":"Approved"}{"fullName":"Jojn Petkobsky","userName":"user1","phone":"12415455","email":"ees#asd.com"date":"11\/16\/2016","time":"1pm ","reason":"ReaReasonReaeason","isApproved":1,"label":"warning","status":"Approved"},{"fullName":"Frank Heinkelman","userName":"user3","phone":"12415455","email":"ees#asddd.com"date":"10\/11\/2016","time":"2pm ","reason":"ReaReasonReaeason","isApproved":1,"label":"warning","status":"Approved"}]
...i can have something like this, so i can have all the booked hours for a given date.
{"12/11/16"😞
{"time" :"10am"},
{"time" :"1pm"},
{"time" :"5pm"}
]
"12/10/16"😞
{"time" :"9am"}
]
}
I tried with something like this, but couldn't really finish it :
$string = file_get_contents("appointments.json");
$json_a = json_decode($string, true);
$date;
$datesTimes = array();
foreach($json_a as $json_r){
if ($json_r['isApproved']==1) {
$date = $json_r['date'];
//another foreach?
}
}
Any help will be appreciated!
As I mentioned in the comments, your JSON is NOT valid so I have fixed it to a point to show how it can be done.
//Fixed JSON as much as I could to show in example.
$json = '
[
{
"fullName": "Jojn Petkobsky",
"userName": "user1",
"phone": "12415455",
"email": "ees#asd.com",
"date": "11\/16\/2016",
"time": "1 pm",
"reason": "ReaReasonReaeason",
"isApproved": "0",
"label": "warning",
"status": "Approved"
},
{
"fullName": "Kitson88",
"userName": "user2",
"phone": "122323325",
"email": "eadasds#asasdasdd.com",
"date": "11\/16\/2016",
"time": "12 pm",
"reason": "ReaReasonReaeason",
"isApproved": "0",
"label": "warning",
"status": "Approved"
},
{
"fullName": "Jamie",
"userName": "user2",
"phone": "122323325",
"email": "eadasds#asasdasdd.com",
"date": "12\/16\/2016",
"time": "8 pm",
"reason": "ReaReasonReaeason",
"isApproved": "0",
"label": "warning",
"status": "Approved"
}
]
';
$array = json_decode($json, true);
//This will be you rnew Array for holding the needed data.
$approved = [];
foreach ($array as $value) {
if ($value['status'] === 'Approved') { //Any check really which will validate Approved
if (array_key_exists($value['date'], $approved)) { //Check if key exists note** will only work on 1D Array
array_push($approved[$value['date']], $value['time']); //If so, then append
} else { //If not, then create it and add value
$approved += [$value['date'] => [$value['time']]];
}
}
}
//Encode back to JSON
$newJson = json_encode($approved);
Output as JSON
{
"11\/16\/2016": ["1 pm", "12 pm"],
"12\/16\/2016": ["8 pm"]
}
http://php.net/manual/en/function.array-key-exists.php
http://php.net/manual/en/function.array-push.php
I have web page which get Json responce like this
{
'hotel_1page':[
{
'id':'10',
'name':'fsf',
'telephone':'233333'
},
{
'id':'11',
'name':'setttttt',
'telephone':'213123123'
},
{
'id':'12',
'name':'fsdfsdf',
'telephone':'122212121'
},
{
'id':'13',
'name':'xxcvcxv',
'telephone':'2147483647'
},
{
'id':'14',
'name':'dssdfg',
'telephone':'2147483647'
},
{
'id':'15',
'name':'dfsdfsdf',
'telephone':'21312321'
},
{
'id':'16',
'name':'fx_test_nw1',
'telephone':'23232323'
},
{
'id':'17',
'name':'fx_test_nw2',
'telephone':'31313131'
}
]
}
and i want to loop through this data and get this data to array and display as html how can i achieve this
this is where i get get json responce,and when i var_dump json encoded variable it says null,where $json variable shows the json responce,
$json = file_get_contents('http://www.example.com/hotel_list.php');
var_dump($json);
$array = json_decode($json, true);
var_dump($array);
The json that you are trying to parse is invalid. Change the single quotes to double quotes and you should be able to parse it to an array.
The JSON documentation says
A value can be a string in double quotes, or a number, or true or false or null, or an object or an array. These structures can be nested.
This should work:
$json = '{ "hotel_1page": [ { "id": "10", "name": "fsf", "telephone": "233333" }, { "id": "11", "name": "setttttt", "telephone": "213123123" }, { "id": "12", "name": "fsdfsdf", "telephone": "122212121" }, { "id": "13", "name": "xxcvcxv", "telephone": "2147483647" }, { "id": "14", "name": "dssdfg", "telephone": "2147483647" }, { "id": "15", "name": "dfsdfsdf", "telephone": "21312321" }, { "id": "16", "name": "fx_test_nw1", "telephone": "23232323" }, { "id": "17", "name": "fx_test_nw2", "telephone": "31313131" } ] }';
echo '<pre>';
var_dump(json_decode($json, true));
echo '</pre>';
I replaced all single quotes with double quotes, that did the trick.
I used single quotes before which caused json_decode to return null
[Edit for usage]
To use the data, you could use something like this:
$obj = json_decode($json, true);
foreach($obj as $row)
{
foreach($row as $key => $item)
{
// $item['id']
// $item['name']
// $item['telephone']
}
}
I'm using a nested foreach() because the id, name and telephone are an array within the hotel_page1 array