How to decode JSON in a loop using PHP and json_decode? - php

I have json like this, returned from service:
{
"reports" : {
"name" : "reports"
"response" : {
"build" : {
"version" : "2.55.10.0",
"name" : "reports-app"
}
},
"status" : 200
},
"static-application" : {
"name" : "static-application"
"response" : {
"app" : {
"name" : "client-frontend",
"description" : "Client Static"
},
"build" : {
"version" : "2.55.10.0",
"name" : "client-frontend"
}
},
"status" : 200
},
"static-help" : {
"name" : "static-help"
"response" : {
"app" : {
"name" : "client-frontend",
"description" : "Client Static"
},
"build" : {
"version" : "2.55.8.0",
"name" : "client-frontend"
}
},
"status" : 200
}
}
And I'm trying to decode it with json_decode:
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, 'https://domainname/api/aggregate/info');
$json = curl_exec($ch);
curl_close($ch);
$data = json_decode($json, true);
echo $data['reports']['name']." | ".$data['reports']['response']['build']['version']."<br \>";
echo $data['static-application']['name']." | ".$data['static-application']['response']['build']['version']."<br \>";
echo $data['static-help']['name']." | ".$data['static-help']['response']['build']['version'];
?>
In return i have:
reports | 2.55.10.0
static-application | 2.55.10.0
static-help | 2.55.8.0
Everything works, but when the service will return more modules, I will have to manually add new echo sections.
How can I write the same in a loop?

You may use a foreach loop to iterate over all $data's modules:
$data = json_decode($json, true);
foreach($data as $module => $data)
{
if(isset($data[$module]['name']) && !empty($data[$module]['response']['build']['version']))
{
echo $data[$module]['name']." | ".$data[$module]['response']['build']['version']."<br \>";
}
}
The foreach let you iterate a single element at a time, without the need to manually handle how many elements it contains.
The empty function checks for the presence of the key in the array and if it contains, in the case it may be missed or empty.

If you want to dynamically output the name and build version of the JSON's sections you can use a foreach() loop to iterate over all items:
$data = json_decode($json);
foreach ( $data as $key => $jsonData ) {
echo $jsonData->name;
echo " | ";
echo $jsonData->response->build->version;
}

Related

PHP update json from received input and write back to same file

I have a json file stored on server & it looks like below:
{
"support_link":"#",
"support_link_2":"#",
"packs":[
{
"identifier":1,
"viewCount":0,
"downloadCount":0
},
{
"identifier":2,
"viewCount":0,
"downloadCount":0
}
]
}
By using PHP, I want to update the viewCount & downloadCount of some of the arrays inside packs.
But the thing is the data is received via a POST method to the server which contains another json with info. of which identifier to update & what param to update, & I am not able to update the existing file & save it back.
Received Json format:
{
"impressions": [
{
"identifier": "1",
"impressionCount": 2
},
{
"identifier": "100",
"impressionCount": 2
},
{
"identifier": "1000",
"impressionCount": 2000
}
],
"downloads": [
{
"identifier": "1",
"downloadCount": 10
}
]
}
What I've tried to do so far:
$json = file_get_contents('php://input');
if ($json != '') {
$properJsonFormatted = json_decode($json, true);
$impressions = $properJsonFormatted['impressions'];
$downloads = $properJsonFormatted['downloads'];
$testConfig =
$json = file_get_contents('php://input');
if ($json != '') {
$properJsonFormatted = json_decode($json, true);
$impressions = $properJsonFormatted['impressions'];
$downloads = $properJsonFormatted['downloads'];
$testConfig = json_decode(file_get_contents("test_config.json"),true);
$packs = $testConfig['packs'];
foreach ($packs as &$pack) {
$packIdentifier = $pack['identifier'];
foreach ($impressions as $impression) {
$impressionIdentifier = $impression['identifier'];
if ($packIdentifier == $impressionIdentifier) {
$pack['viewCount'] += $impression['impressionCount'];
$newCount = $pack['viewCount'];
print("Id: $packIdentifier, ViewCount: $newCount\n");
}
}
}
put_file_contents("test_config.json" , $testConfig);
// print_r($testConfig);
// Save back the updated test_config.json
}
}
UPDATE
Seem to have misinterpreted the question. The actual problem seems to be much simpler.
Change this:
put_file_contents("test_config.json" , $testConfig);
To this:
file_put_contents('test_config.json', json_encode($testConfig));
Also change this:
$packs = $testConfig['packs'];
To this:
$packs = &$testConfig['packs'];
As it seems you forgot to assign that by reference, while you correctly did that in the foreach.

Notice: Trying to get property of non-object in in json

<?php
$json= '{
"fields" :
[
{
"name" : "news_title",
"type" : "text",
"value" : "old title"
},
{
"name" : "news_content",
"type" : "textarea",
"value" : "old content"
}
]
}';
echo $json;
$jsonInPHP = json_decode($json,true);
$results = count($jsonInPHP['fields']);
for ($r = 0; $r < $results; $r++){
// look for the entry we are trying to find
if ($jsonInPHP->fields[$r]['name'] == 'news_title'
&& $jsonInPHP->fields[$r]->value == 'old title'){
// remove the match
unset($jsonInPHP->fields[$r]);
if(empty($jsonInPHP->fields[$r]->value))
{
$jsonInPHP['fields'][$r]['name'] == 'news_title';
$jsonInPHP->fields[$r]->value=='no';
}
break;
}
}
function gog($status)
{
$results = count($status->fields);
for ($r = 0; $r < $results; $r++){
$status->fields[$r]->value == 'old rr';
}
}
$jsonInPHP->fields = array_values($jsonInPHP->fields);
echo json_encode($jsonInPHP);
?>
i want to change after searching from
'{"fields":[{"name":"news_title","type":"text","value":"old title"},{"name":"news_content","type":"textarea","value":"old content"}]}'
to
'{"fields":[{"name":"news_title","type":"text","value":"My new title"},{"name":"news_content","type":"textarea","value":"My new content"}]}'
Check official docs of json_decode Second parameter of function json_decode($json,true); (in your case true) determines whether result will be converted to associative array. If you want to use result as objects set that value to false or better omit that at all.

Json to url with php

In my $output there is this:
{
"status" : "success",
"data" : {
"network" : "BTC",
"addresses" : [
{
"user_id" : 0,
"address" : "3ABR5GohqyXzf2zebYwjmLuwV7vtFZw1BZ",
"label" : "default",
"available_balance" : "0.00000000",
"pending_received_balance" : "0.00000000"
}
]
}
}
But now I want it to get to redirect like:
https://example.com/index.php?status=succes&network=BTC
etc. etc.
But $output can change to like:
{
"status" : "success",
"data" : {
"network" : "BTC",
"available_balance" : "0.00000000",
"pending_received_balance" : "0.00000000"
}
}
But then I still want it to work.
I don't know PHP enough for this, so I want to ask:
How to do this?
Simply json_decode() and access the status and network properties:
$decoded = json_decode($output);
header('Location: https://example.com/index.php?status=' . urlencode($decoded->status) . '&network=' . urlencode($decoded->data->network));
exit();
Get the data in the json as an array:
$url = 'https://example.com/index.php?status=' . $status;
foreach($data as $param->$value) {
$url += '&' . $param . '=' . $value
}
header('Location:' $url);
Been a while since i've worked in php but this should handle a varying amount of parameters.

JSON to Database with php

So I have this JSON for example
{
"top" : [
{
"info" : {
"ID" : 0,
"TID" : 1
},
"geo" : {
"poins" : [
[
[
-5.9,
57.1
],
[
-5.99,
57.0
]
]
]
}
},
{
"info" : {
"ID" : 1,
"TID" : 2
},
"geo" : {
"points" : [
[
[
-5.4,
57.0
],
[
-5.9,
57.0
]
]
]
}
}
]
}
I need to put this information in the DataBase with php
So I have a colum in the DB called points and it need the data inside to be looking like:
[-5.4, 57.0],[-5.9, 57.0]
I have a columb with ID so all I need is to put the points from the JSON for every ID
My php should be loking like:
connection to the database
$str = file_get_contents(the JSON);
$json = json_decode($str, true);
foreach ($json['top'] as $field) {
query='UPDATE poins_table
SET points='$field['geo']['points']'
WHERE ID='$field['info']['ID']' '
}
The code seems to be not working. What I am missing ...Any siggestions will be helpfull. Thank you
You could try following:
<?php
$str = file_get_contents('the JSON URL');
$json = json_decode($str, true);
try{
$db = new PDO("dbtype:host=yourhost;dbname=yourdbname;charset=utf8","username","password");
$query = $db->prepare('UPDATE poins_table SET points=? WHERE ID=?');
foreach ($json['top'] as $field) {
$query->execute(array(json_encode($field['geo']['points']), $field['info']['ID']));
}
} catch(PDOException $e) {
echo "Error: ". $e;
}
?>

how to parse json data in php

I have json result from API like:
{
"pagination":
{
"results" : 2248,
"page" : 1,
"page_size" : 200,
**"pages" : 12**
},
"products" :
[ {"id": "370c3876-a2b9-11e2-b2b4-bc764e10976c", "source_id": "",....}]}
I would like to retrieve "pages" : 12 from pagination. How can I do it?
I tried this and it worked fine
$data = ' {
"pagination":
{
"results" : 2248,
"page" : 1,
"page_size" : 200,
"pages" : 12
}
}';
$response = json_decode($data, true);
echo $response['pagination']['pages'];//12
Use json_decode to decode the api response, then access the property.
Example:
$response = json_decode($data, true);
echo $response['pagination']['pages'];
<?php
$object = json_decode($your_api_return_string);
$pages = $object->pagination->pages;
echo $pages;
?>

Categories