Print JSON keys of an array within another array in PHP [duplicate] - php

This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 4 years ago.
I have the following JSON code:
{
"google.com": {
"clicks": 23,
"browsers": {
"Chrome": 19,
"Mozilla": 2,
"Safari": 1
}
},
"mcnitro.net": {
"clicks": 87,
"browsers": {
"Chrome": 19,
"Mozilla": 2,
"Safari": 1
}
}
}
And I am endeavouring to print on the document page the arrays' names and their children.
So far, I have tried the following PHP code:
<?php
header("Content-type: text/javascript");
$jsonString = file_get_contents('stats.json');
$data = json_decode($jsonString, true);
foreach($data->children() as $domain) {
echo $data[$domain];
foreach($data[$domain] as $value) {
echo $value['clicks'];
}
}
?>
However, I am facing an issue in the error_log:
PHP Fatal error: Call to a member function children() on array in /home/gamin167/public_html/ads/engine/300x250/gen.js.php on line 5
The result wanted was to have "google.com" and "mcnitro.net" printed, as well as their "clicks" property.
Any tip or advice will be highly appreciated! Thanks in advance!

You decode the string to an array with true yet you seem to try and use it as an object.
Also there is no need to loop twice.
foreach($data as $key => $domain) {
echo $key . "\n";
echo $domain['clicks'] . "\n\n";
}
output:
google.com
23
mcnitro.net
87
https://3v4l.org/D7FCY

You cannot use ->children(). $data is an array with your json data, and you can use foreach to get key and value, like foreach ($data as $key => $value).
So here, to get your domain name, just do :
<?php
header("Content-type: text/javascript");
$jsonString = file_get_contents('stats.json');
$data = json_decode($jsonString, true);
foreach($data as $domain => $value) {
echo $value['clicks'];
}
?>

Related

How to update/edit a JSON using PHP [duplicate]

This question already has answers here:
PHP foreach change original array values [duplicate]
(5 answers)
How to update/edit a JSON file using PHP [closed]
(1 answer)
Closed 2 years ago.
Please help me!
JSON:
{
"1":{
"TchID":"G303992",
"TchData":{
"TchID":"G303992",
"TchNama":"G303992",
"TchPassword":43511824
}
},
"2":{
"TchID":"G141843",
"TchData":{
"TchID":"G141843",
"TchNama":"G141843",
"TchPassword":22932450
}
}
}
How to update value in nested object from
"2":{
"TchID":"G141843",
"TchData":{
"TchID":"G141843",
"TchNama":"G141843",
"TchPassword":22932450
}
}
to
"2":{
"TchID":"G141843",
"TchData":{
"TchID":"G141843",
"TchNama":"Alex J",
"TchPassword":22932450
}
}
in php script?????
You see that i want to change "TchNama":"G141843" to "TchNama":"Alex J"
Here my code
<?php
$data = '{"1":{"TchID":"G303992","TchData":{"TchID":"G303992","TchNama":"G303992","TchPassword":43511824}},"2":{"TchID":"G141843","TchData":{"TchID":"G141843","TchNama":"G141843","TchPassword":22932450}}}';
$guru = json_decode($data);
foreach ($guru as $items){
if($items['TchID'] == 'G303992'){
// i dont know how to change $items['TchData']['TchNama'] = 'G141843' to 'Alex J'
$viewchange = json_encode($guru);
echo $viewchange;
}
}
?>
You can covert the json string to an array-object using json_encode($,TRUE).
Then you will be able to loop through the keys of the object if you obtain the keys by array_keys().
And then you can either use a separate variable to iterate through the main object properties and change that object, or directly access the main object and change it at the source, which is what I did below:
$data = '{"1":{"TchID":"G303992","TchData":{"TchID":"G303992","TchNama":"G303992","TchPassword":43511824}},
"2":{"TchID":"G141843","TchData":{"TchID":"G141843","TchNama":"G141843","TchPassword":22932450}}}';
$guru = json_decode($data, true);
$keys = array_keys($guru);
foreach ($keys as $key) {
if($guru[$key]['TchID'] == 'G303992'){
$guru[$key]["TchNama"] = "Alex J";
}
}
$viewchange = json_encode($guru);
echo $viewchange;
Please try this.
$data = '{"1":{"TchID":"G303992","TchData":{"TchID":"G303992","TchNama":"G303992","TchPassword":43511824}},"2":{"TchID":"G141843","TchData":{"TchID":"G141843","TchNama":"G141843","TchPassword":22932450}}}';
$guru = json_decode($data);
var_dump($guru);
foreach ($guru as $items) {
if ($items->TchID == 'G141843') {
$items->TchData->TchNama = "Alex J";
}
}
var_dump($guru);
$viewchange = json_encode($guru);
echo $viewchange;

(PHP, JSON) Foreach [duplicate]

This question already has answers here:
How can I combine two strings together in PHP?
(19 answers)
Closed 4 months ago.
I have a question about php and json. Im running this php in foreach loop. But when i get all the tank_id from the json file. I get results like
8011819314145
I want it to display like:
Tank ID: 801
Tank ID: 18193
Tank ID: 14145
What i'm doing wrong? Help me thank you.
Here is my php file:
<?php
$json = file_get_contents("https://api.worldoftanks.eu/wot/account/tanks/?application_id=demo&account_id=521997295");
$json_tank = json_decode($json, TRUE);
foreach ($json_tank['521997295'] as $tank_id) {
echo $tank_id['tank_id'];
}
?>
In a foreach you can get both the key and the value. Take a look at the following pseudo-code
foreach ($array as $key => $value) {
echo $key.': '.$value.'<br />';
}
<?php
$json = file_get_contents("https://api.worldoftanks.eu/wot/account/tanks/?application_id=demo&account_id=521997295");
$json_tank = json_decode($json, TRUE);
echo('<pre>');
//print_r($json_tank);
foreach ($json_tank['data']['521997295'] as $tank_id) {
echo "Tank ID: " . $tank_id['tank_id'] . '<br/>';
}
You just need to format output as you want.
<?php
$json = file_get_contents("https://api.worldoftanks.eu/wot/account/tanks/?application_id=demo&account_id=521997295");
$json_tank = json_decode($json, TRUE);
foreach ($json_tank['521997295'] as $tank_id) {
echo 'Tank ID: '.$tank_id['tank_id'].' ';
}
?>

Issues with decoding json object

Thanks for your time in reading this post.
My php file is receiving a json object. But I am facing issues while decoding it.
My php code:
$data=$_POST['arg1'];
echo $data;
$json = json_decode($data,true);
echo $json;
$i = 1;
foreach($json as $key => $value) {
print "<h3>Name".$i." : " . $value . "</h3>";
$i++;
}
When I echo data results as below.
{
"SCI-2": {
"quantity": 2,
"id": "SCI-2",
"price": 280,
"cid": "ARTCOTSB"
}
}
When I echo $json, result is as it follows :
Array
Name1 : Array.
Please assist as i need tho access the cid and quantity values in the $data.
json_decode returns an array. And to print array you can use print_r or var_dump.
Now to access your values you can try :
$json["SCI-2"]["quantity"] for quantity and $json["SCI-2"]["cid"] for cid.
Demo : https://eval.in/522350
To access in foreach you need this :
foreach($json as $k) {
foreach($k as $key => $value) {
print "<h3>Name".$i." : " . $value . "</h3>";
}
}
Since you do not know the number of items in your object, use this:
$obj = json_decode($json);
After this, iterate the $obj variable and after that, inside the loop, use the foreach to get each property.
foreach($iteratedObject as $key => $value) {
//your stuff
}

JSON manipulation in 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

Get data from JSON file with PHP [duplicate]

This question already has answers here:
How to loop through PHP object with dynamic keys [duplicate]
(16 answers)
Closed 4 years ago.
I'm trying to get data from the following JSON file using PHP. I specifically want "temperatureMin" and "temperatureMax".
It's probably really simple, but I have no idea how to do this. I'm stuck on what to do after file_get_contents("file.json"). Some help would be greatly appreciated!
{
"daily": {
"summary": "No precipitation for the week; temperatures rising to 6° on Tuesday.",
"icon": "clear-day",
"data": [
{
"time": 1383458400,
"summary": "Mostly cloudy throughout the day.",
"icon": "partly-cloudy-day",
"sunriseTime": 1383491266,
"sunsetTime": 1383523844,
"temperatureMin": -3.46,
"temperatureMinTime": 1383544800,
"temperatureMax": -1.12,
"temperatureMaxTime": 1383458400,
}
]
}
}
Get the content of the JSON file using file_get_contents():
$str = file_get_contents('http://example.com/example.json/');
Now decode the JSON using json_decode():
$json = json_decode($str, true); // decode the JSON into an associative array
You have an associative array containing all the information. To figure out how to access the values you need, you can do the following:
echo '<pre>' . print_r($json, true) . '</pre>';
This will print out the contents of the array in a nice readable format. Note that the second parameter is set to true in order to let print_r() know that the output should be returned (rather than just printed to screen). Then, you access the elements you want, like so:
$temperatureMin = $json['daily']['data'][0]['temperatureMin'];
$temperatureMax = $json['daily']['data'][0]['temperatureMax'];
Or loop through the array however you wish:
foreach ($json['daily']['data'] as $field => $value) {
// Use $field and $value here
}
Demo!
Use json_decode to transform your JSON into a PHP array. Example:
$json = '{"a":"b"}';
$array = json_decode($json, true);
echo $array['a']; // b
Try:
$data = file_get_contents ("file.json");
$json = json_decode($data, true);
foreach ($json as $key => $value) {
if (!is_array($value)) {
echo $key . '=>' . $value . '<br/>';
} else {
foreach ($value as $key => $val) {
echo $key . '=>' . $val . '<br/>';
}
}
}

Categories