JSON manipulation in PHP? - php

I need to edit some data in a JSON file, and I'm looking to do so in PHP. My JSON file looks like this:
[
{
"field1":"data1-1",
"field2":"data1-2"
},
{
"field1":"data2-1",
"field2":"data2-2"
}
]
What I've done so far is $data = json_decode(file_get_contents(foo.json)) but I have no idea how to navigate this array. If for example I want to find the data from the first field of the second object, what's the PHP syntax to do so? Also, are there other ways I should know about for parsing JSON data into a PHP friendly format?

This JSON contains 2 arrays with 2 objects each, you can access like this:
$arr = json_decode(file_get_contents(foo.json));
// first array
echo $arr[0]->field1;
echo $arr[0]->field2;
// second array
echo $arr[1]->field1;
echo $arr[1]->field2;
if you convert this to an array and avoid objects you can then access like this:
$arr = json_decode(file_get_contents(foo.json), true);
// first array
echo $arr[0]['field1'];
echo $arr[0]['field2'];
// second array
echo $arr[1]['field1'];
echo $arr[1]['field2'];

$data = json_decode(file_get_contents(foo.json));
foreach($data as $k => &$obj) {
$obj->field1 = 'new-data1-1';
$obj->field2 = 'new-data1-2';
}

Please use this code to navigate through your json format. This code is dynamic and can navigate for any number of objects you have in your result.
<?php
$json ='[
{
"field1":"data1-1",
"field2":"data1-2"
},
{
"field1":"data2-1",
"field2":"data2-2"
}
]';
if($encoded=json_decode($json,true))
{
echo 'encoded';
// loop through the json values
foreach($encoded as $key=>$value)
{
echo'<br>object index: '.$key.'<br>';
foreach($value as $bKey=>$bValue)
{
echo '<br> '.$bValue.' = '.$bValue;
}
}
// get a perticular item
echo '<br>object[0][field1]: '.$encoded[0]['field1'];
}
else
{
echo'error on syntax';
}
?>
Which will have following output
encoded
object index: 0
data1-1 = data1-1
data1-2 = data1-2
object index: 1
data2-1 = data2-1
data2-2 = data2-2
object[0][field1]: data1-1

Related

Read and print json array in php

I have a JSON array like below. I want to print only the values of the name. But I am getting undefined index name and getting value of name.below is my json.
[{"docId":{"id":"57dd70252a896558e573a0c8"},"docProfile":{"name":"gowtham","gender":null,"email":null,"mobile":"7406339908"},"docLocalInfo":{"username":"gowtham","otp":934343,"newPasswordToken":null,"tempMobile":"","adminVerfiy":null},"privateInfo":{"mciNumber":null,"aadharNumber":null,"panNumber":null},"tempHospitals":[],"bankInfo":null,"signupSteps":{"accountCreated":true,"otpValidated":true},"notification":null,"hospitals":[],"address":null}]
my code
foreach($doc_array as $data => $mydata)
{
foreach($mydata as $key=>$val)
{
echo $val['name'];
}
}
How to get the values of name from docProfile? Any help would be greatly appreciated
Inside your foreach you don't need to loop again since docProfile is an index of the json object array
Just simple access it
echo $mydata['docProfile']['name'].'<br>';
so your foreach would be like this
foreach($doc_array as $data => $mydata) {
echo $mydata['docProfile']['name'].'<br>';
}
Demo
Try to something Like this.
<?php
$string = '[{"docId":{"id":"57dd70252a896558e573a0c8"},"docProfile":{"name":"gowtham","gender":null,"email":null,"mobile":"7406339908"},"docLocalInfo":{"username":"gowtham","otp":934343,"newPasswordToken":null,"tempMobile":"","adminVerfiy":null},"privateInfo":{"mciNumber":null,"aadharNumber":null,"panNumber":null},"tempHospitals":[],"bankInfo":null,"signupSteps":{"accountCreated":true,"otpValidated":true},"notification":null,"hospitals":[],"address":null}]';
$arr = json_decode($string, true);
echo $arr[0]['docProfile']['name'];
?>
This array just have one row but if your array have more row you can use it;
you need to decode JSON at first.
$doc_array =json_decode($doc_array ,true);
foreach($doc_array as $key=> $val){
$val['docProfile']['name']
}
<?php
$json_str='[{"docId":{"id":"57dd70252a896558e573a0c8"},"docProfile":{"name":"gowtham","gender":null,"email":null,"mobile":"7406339908"},"docLocalInfo":{"username":"gowtham","otp":934343,"newPasswordToken":null,"tempMobile":"","adminVerfiy":null},"privateInfo":{"mciNumber":null,"aadharNumber":null,"panNumber":null},"tempHospitals":[],"bankInfo":null,"signupSteps":{"accountCreated":true,"otpValidated":true},"notification":null,"hospitals":[],"address":null}]';
$json_arr = (array)json_decode($json_str,true);
foreach($json_arr as $iarr => $ia)
{
foreach($ia["docProfile"] as $doc => $docDetails)
{
if($doc =="name")
{
echo $ia["docProfile"]["name"];
}
}
}
?>
This code gives you the answer

How to parse through multiple layers of JSON

I have some JSON I need to parse in a file test.json.
{
"players":
[
{ "SteamId":123, "Username":"Bob", "Kills":5, "Deaths":7, "Rank":1 },
{ "SteamId":456, "Username":"Nick", "Kills":3, "Deaths":2, "Rank":2 },
{ "SteamId":789, "Username":"Moses" "Kills":8, "Deaths":1, "Rank":3 }
]
}
How can I loop through and display my data. My code so far when I var_dump gives me a NULL
$raw_data = file_get_contents('test.json');
$data = json_decode($raw_data, true);
var_dump($data);
Your code is fine once you place the comma Saty mentioned.
To loop and print some values it would look something like:
foreach($data["players"] as $player){
print "Steam ID: ".$player['SteamId'];
print "Username: ".$player['Username'];
print "Kills: ".$player['Kills'];
print "Deaths: ".$player['Deaths'];
print "Rank: ".$player['Rank'];
}
This could be improved to automatically use the Key value as output with the following:
foreach($data["players"] as $player){
foreach($player as $key => $value){
print $key.": ".$value;
}
}
Depends what you are trying to accomplish and how the data will be viewed, but I expect you would be using HTML template.

How to get values of a json array in php?

I have json like this:
{
"Products": [
{
"_id": 1
....
},
{
"_id": 2
....
}
]
}
And got this json :
$str = file_get_contents($_FILES["uploadFile"]["tmp_name"]);
// convert object => json
$json = json_encode($str);
// convert json => object
$decoded = json_decode($json,true);
Now i want to see all _id of Producs.
I use this echo $decoded[0]['_id']; but it shows nothing.
Any ideas?
$decoded = json_decode($json, true);
echo $decoded['products'][0]['_id'];
This decodes the json as an array that you can use just like any other array in PHP, if you have trouble accessing values, then simply do a print_r($decoded) and that should show you its structure
If you want to loop over all the ids, then simply do a foreach loop
foreach($decoded as $inner_array) {
foreach($inner_array as $products) {
echo $products['_id'];
}
}
Working demo
You should be aware of using quotes on your json string :)
keys and values .
You don't need to encode it. the string is already in json format
$str= '{"Products": [{"_id": "1"},{"_id": "2"}]}';
$decoded = json_decode($str,true);
echo $decoded['Products'][0]['_id'];

How to loop json and parse the value

This is my php code [EDITED]:
$redis_data = file_get_contents("http://example.org/data/data.txt");
That code returns the following json data:
{"Phone":"08XXXXX","StartTime":"121212","Customer":"Customer A","time":1407921302}
{"Phone":"08XXXXX0","StartTime":"111111","Customer":"Customer B","time":1407921302
{"Phone":"08XXXXX","StartTime":"131313","Customer":"Customer C","time":1407921302}
This is my code to looping parse the value:
$redis_data = file_get_contents("http://example.org/data/data.txt");
$redis_data = json_decode($redis_data, true);
foreach ($redis_data as $data) {
echo $data['Phone'];
echo "<br>";
}
But I got this errors:
Invalid argument supplied for foreach()
What am I doing wrong?
The data you trying to get is not well formatted json
[{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName": "Jones"}]
This is the json syntax.
and you are getting data in following format.
{"ANumber":"08122378673","BNumber":"500046","StartTime":"08122014102113","EndTime":"08122014104126","TrunkA":"S1JK2SBD1S","TrunkB":"N7JK2GSM1B","Customer":"PT.BNI","time":1407921302}
{"ANumber":"081351607600","BNumber":"14000","StartTime":"08122014102406","EndTime":"08122014103738","TrunkA":"S1JK2SSB1S","TrunkB":"EPJK2MNR0","Customer":"Bank Mandiri (CC_IB_Jasnita)","time":1407921302}
You may need to reformat your data string
You're trying to loop JSON - not PHP. You need to run json_decode (docs) on the your $redis_data variable before attempting to loop it.
$redis_data = json_decode($redis_data, true);
You need to decode the json before you can loop through it.
$redis_data = json_decode(file_get_contents("http://example.com/tes_files/data.txt"), true);
foreach ($redis_data as $data) {
echo $data['phone'];
}
Here is solution
$redis_data = explode( chr(10), file_get_contents("http://example.com/tes_redis/data.txt"));
foreach ($redis_data as $data) {
var_dump(json_decode($data));
$data = json_decode($data);
echo $data->Phone;
echo $data->StartTime;
echo $data->Customer;
//echo $data->ANumber;
//echo $data->BNumber;
}
you need to export data first.
first you have to convert json to array using json_decode function it will give array and after that you can loop
`
$jsonString =
'[{"Phone":"08XXXXX","StartTime":"121212","Customer":"Customer A","time":1407921302},
{"Phone":"08XXXXX0","StartTime":"111111","Customer":"Customer B","time":1407921302},
{"Phone":"08XXXXX","StartTime":"131313","Customer":"Customer C","time":1407921302} ]';
$array=json_decode($jsonString);
foreach ($arrayOfEmails as $data) {
echo $data->Phone."<br>";
}
`

loop json array and return values in php

I use a library for Synchronize a local WebSQL DB to a server specifically https://github.com/orbitaloop/WebSqlSync. I use PHP: 5.4.7
this is json var $json
{
"info":"",
"data":{
"clientes":[],
"conceptos_gastos":[],
"formaspago":[{
"idFormaPago":7,
"FormaPago":"quwuw",
"Dias":1,
"Cuotas":1,
"last_sync_date":null
}],
"listaprecios":[],
"producto":[],
"repartidores":[],
"tipodocumento":[],
"vehiculos":[],
"zonas":[]
}
}
when I try to get the values
$js=json_decode($json,true);
foreach ($js['formaspago'] as $row ) {
echo $row["Formapago"];
}
I get this error:
Invalid argument supplied for foreach
any help is appreciated
use json_decode
//array
$data = json_decode($json, true);
foreach($data["data"]["formaspago"] as $row) {
echo $row["Formapago"];
}
Thanks #JimL for the hint.
You're not passing a valid array to the foreach loop. However, even if you parse the json you've supplied, a foreach won't work because it's an object not an array.
$json = '{
"info":"",
"data":{
"clientes":[],
"conceptos_gastos":[],
"formaspago":[{
"idFormaPago":7,
"FormaPago":"quwuw",
"Dias":1,
"Cuotas":1,
"last_sync_date":null
}],
"listaprecios":[],
"producto":[],
"repartidores":[],
"tipodocumento":[],
"vehiculos":[],
"zonas":[]
}
}';
$obj = json_decode($json);
print $obj->info will return an empty string.
$obj->data is an object that has various properties some of which are empty arrays. Passing these into the foreach should work. i.e.
foreach($obj->data->clients as client) {
// Do something here
}
Further, $obj->data->formaspago has exactly one element in the array, which is an object. You can access this object with a foreach loop:
foreach($obj->data->formaspago as formaspago) {
print formaspago->idFormaPago; // Will print 7
print formaspago->FormaPago; // Will print "quwuw"
print formaspago->Dias; // Will print 1
print formaspago->Cuotas; // Will print 1
print formaspago->last_sync_date; // Will print nothing
}

Categories