I have a json file:
$json='[{"Email":"myemail1#domain.com","Name":"company 1","Tel1":"xx-xx-xx","Adresse":"XXXXXX"},{"Email":"myemail2#domain.com","Name":"Company 2","Tel1":"xx-xx-xx","Adresse":"XXXXXX"}]';
and my forms post data in variable
vars="fname"=>"Ameur","lname"=>"KHIL"
"fname"=>"Marak","lname"=>"Cristo"
and I like to insert in between my json content with variable to get the final json like this:
$result='[{"Email":"myemail1#domain.com","Name":"company 1","vars":{"fname":"Ameur","lname":"KHIL","Tel1":"xx-xx-xx","Adresse":"XXXXXX"}},{"Email":"myemail2#domain.com","Name":"Company 2","vars":{"fname":"Marak","lname":"Cristo","Tel1":"xx-xx-xx","Adresse":"XXXXXX"}}]';
For this purpose you can use json_decode() to parse the JSON-String to a PHP-Object. Then you just set a new value vars to the given form values.
Parsing the JSON-String
$json = json_decode('[{"Email":"myemail1#domain.com","Name":"company 1","Tel1":"xx-xx-xx","Adresse":"XXXXXX"},{"Email":"myemail2#domain.com","Name":"Company 2","Tel1":"xx-xx-xx","Adresse":"XXXXXX"}]');
Adding the new vars value and removing the additional ones. This is just for the first entry but you can do the same for the other entry or even iterate through the array for multiple entries
$json[0]->vars = ["fname" => "Marak", "lname" => "Cristo", "Tel1" => $json[0]->Tel1,"Adresse" => $json[0]->Adresse];
unset($json[0]->Tel1);
unset($json[0]->Adresse);
And getting your result in a JSON-String
$result = json_encode($json);
Related
How to add another object with value in data?
Something start like :
$data=[{name:"apple"}]
And i wanted output like this
$data=[{name:"apple",city:"gotham"}]
Dont try and build JSON manually, create a PHP data structure that you want and then use json_encode() to make it into a JSON String
$d = [(object)['name' => 'apple', 'city' => 'gotham']];
echo json_encode($d);
RESULT
[{"name":"apple","city":"gotham"}]
If some values already exists, you should decode it to a PHP data struture and then add to it and convert back to JSON String
$data='[{"name":"apple"}]';
$d = json_decode($data);
$d[0]->city = 'Gotham';
$data = json_encode($d);
RESULT
[{"name":"apple","city":"Gotham"}]
I am working on a project where a user has to fill up a form and can upload multiple documents. Everytime he uploads a document, he calls a webservice which returns a JSON file with id and type.
Since he can upload multiple documents so the webservice is called many times. When he completes his form and submits it, I need to send a json with the multiple id and type that I have received previously from JSON.
This is the JSON that I need to send to the server when the user finally submits the form:
"docls":[
{
"id":"123",
"ty":"101",
},
{
"id":"456",
"ty":"102",
}
],
How do I encode the JSON when I dont know how many files the user has uploaded?
P.S. I have already been able to get the response from the first JSON in the form of 'id' and 'ty'. Do I need to store it in array? If yes then how do I decode it into json?
$json_string = array(
'docls' => array (
'id' => '123',
'ty' => '101',
),
);
You're going to want to build the array with php then json_encode it when your ready to send it back to the server
// Create an array to hold the documents
$documents = [];
// push each document into the array as the user does their thing
$documents[$id] = $ty;
// When the user is finished
$json = json_encode($documents);
Well, you just have to use json_decode to convert json string you receive to php array, and json_encode to convert convert php array to json formatted string.
Check this example:
<?php
$json = '{"foo-bar": 12345}';
$obj = json_decode($json);
print $obj->{'foo-bar'}; // 12345
?>
more information here
I am trying to get json data from the Statcounter API.
I have the following:
$query = makeQuery("2292634", "demo_user", "statcounter", "visitor", "");
echo $query . "<br>";
$response = file_get_contents($query, true);
$data = json_decode($response, true);
echo $data['sc_data']['log_visits'];
I know the query is correct, and I know the $response is filled with unformatted json. The trouble is accessing the array and pulling the values out.
Here are the first couple lines of the unformatted json it is giving me.
This link will only work for 15 minutes, I can generate a new one if you would like to see the raw json.
http://api.statcounter.com/stats/?vn=3&s=visitor&pi=2292634&t=1398791335&u=demo_user&sha1=c6cdfd6c84227801c6ca758c17252712e3f76514
{"#attributes":{"status":"ok"},"sc_data":[{"log_visits":"1","entries_in_visit":"2","entry_t":"2014-04-29 17:57:33","entry_url":"http:\/\/www.guitar-online.com\/en\/","entry_title":"Learn how to play the guitar: tutorials, guitar
Obviously I am not accessing the array in the correct way...but I haven't found the syntax to make it work YET!
Thank you for your help.
Looking at your data, sc_data is an array containing nested JSON objects so you should be able to iterate over that array to read the data like you want:
echo $data['sc_data'][0]['log_visits'];
The code above will access the first element of the array sc_data and print the value of log_visits
When you have {"field":['a','b','c']} in JSON, you would access 'a' as field[0].
The elements of the array can be any valid value, i.e.
string
number
object
array
true
false
null
In your case it is objects and you access that object the same way you would access any other array element - by the index number (JSON doesn't have associative array of type "key" => "value")
In my php file im using the following,
$obj = ($_POST['data']);
var_dump(json_decode($obj,true));
And i see this result. Is this the correct format? and how do i access the array.
eg, set a new variable $newID the same as row1 id
array(4) {
["row0"]=>
string(92) "{"id":"157","name":"123","basic":"123123123","submitter":"Keith","status":"review"}"
["row1"]=>
string(169) "{"id":"158","name":"TEST RESOURCE","basic":"Please state the type of work.","submitter":"Keith","status":"review"}"
["row2"]=>
string(107) "{"id":"159","name":"TEST OTHER","basic":"testing for other","submitter":"Keith","status":"review"}"
["row3"]=>
string(160) "{"id":"160","name":"Name","basic":"type of work","submitter":"Keith","status":"review"}"
}
heres whats in POST in firebug
data {"row0":"{\"id\":\"157\",\"name\":\"123\",\"basic\":\"123123123\",\"submitter\":\"Keith\",\"status\":\"review\"}","row1":"{\"id\":\"158\",\"name\":\"TEST RESOURCE\",\"basic\":\"Please state the type of work.\",\"submitter\":\"Keith\",\"status\":\"review\"}","row2":"{\"id\":\"159\",\"name\":\"TEST OTHER\",\"basic\":\"testing for other\",\"submitter\":\"Keith\",\"status\":\"review\"}","row3":"{\"id\":\"160\",\"name\":\"Name\",\"basic\":\"type of work\",\"submitter\":\"Keith\",\"status\":\"review\"}"}
Each "row" of the array is another JSON string. It seems like the data was double-encoded, like:
$array = json_encode(
array(
'row0' => json_encode(array('id' => '157', ...)),
...
)
)
This is incorrectly encoded data, unless you wanted JSON objects inside JSON objects. To work with it, you need to json_decode each individual item again. Better though: fix the encoding step.
I'm grabbing data from a mysql database and encoding a JSON object with PHP to use in JS.
On the PHP end, I did this
while($row = mysql_fetch_array($result))
{
$jmarkers = array(
'id'=> $row['id'],
'lat' => $row['lat'],
'lng' => $row['lng'],
etc...
);
array_push($json, $jmarkers);
}
$jsonstring = json_encode($json);
echo $jsonstring;
I can access the data in JS using jQuery, and I made an array to save the JSON data:
$.getJSON("getjson.php", function(data)
{
myMarkers = data;
console.log(myMarkers);
});
I'd planned to access the data in the myMarkers array inside loop, with a statement like this:
var tempLat = myMarkers.jmarkers[i].lat;
The problem is my JSON objects aren't called jmarkers or anything else, they have this generic name "Object" when I print them to the console:
Object { id="2", lat="40.6512", lng="-73.9691", more...},
So I'm not sure how to point to them in my JS array. I looked the PHP JSON encode function and I can't see where to set or change the object name. Any suggestions? Thank you!
That's to be expected. JSON is essentially the right-hand-side of an assignment operation:
var x = {'foo':'bar'};
^^^^^^^^^^^^^---- JSON
The x part is not included, since that's simply the name of the object. If you want your jmarkers text included, it'll have to be part of the data structure you're going to encode:
$arr = array(
'jmarkers' => array(...your data here...);
);
But all this does is add another layer to your data structure for no useful reason.
$jmarkers is simply the identifier on the PHP side for the JSON object. When it gets passed, it converts the array value into a JSON-encoded string and therefore loses the identifier as a result.
In your PHP code at the moment, array_push($json, $jmarkers) is appending an array to your current $json array. You are therefore instancing a two-dimensional array, which will not be retrievable by the jmarkers identifier in your Javascript code. Simply retrieve the data using myMarkers[i] instead.
You... don't. The whole thing is an object. You only need to refer to the elements within.
alert(myMarkers.id);