Name of the JSON response in a ForEach in PHP - php

I am working on a small projet with a specific JSON API
I got this JSON from response of the API.
{
"3": {
"email": "email#domain.com",
"ext": "100",
"location": "remote",
"name": "Test Extension",
"protocol": "sip",
"status": "enabled",
},
"66": {
"email": "support#domain.com",
"ext": "101",
"location": "remote",
"name": "Test2",
"protocol": "sip",
"status": "enabled",
}
}
I want to get result like that:
Extension: 100
Nom: Test Extension
ID: 3
Status: enabled
Extension: 101
Nom: Test2
ID:66
Status: enabled
I cannot find the way to get the ID for each of the array...
My code is :
$json = file_get_contents($list);
$queries = json_decode($json);
foreach($queries as $query){
echo "<br>Extension: ";
echo $query->ext;
echo "<br>Nom: ";
echo $query->name;
echo "<br>";
echo "ID:";
echo $id;
echo "<br>";
echo " Status: ";
echo $query->status;
echo "<br>";
}

using foreach itself you can get index
foreach($queries as $id => $query){
echo "<br>Extension: ";
echo $query->ext;
echo "<br>Nom: ";
echo $query->name;
echo "<br>";
echo "ID:";
echo $id;
echo "<br>";
echo " Status: ";
echo $query->status;
echo "<br>";
}

Related

foreach loop for multidimensional array in php

I have a multidimensional array with key value. I want to loop the data in that array but I don't know how.
This is my array:
{
"success": "1",
"order_details": [
{
"item_order": 5,
"address": "155, Mani Nagar Society, Nana Varachha, Surat, Gujarat 395006, India",
"contact": "95303709",
"total_price": "3330.0",
"order_place": "18-05-25 06-07-20",
"preparing_date_time": "",
"preparing_status": "Deactivate",
"dispatched_date_time": "",
"dispatched_status": "Deactivate",
"delivered_date_time": "",
"delivered_status": "Deactivate",
"menu": [
{
"menu_name": "demo item",
"item_amt": "200",
"Ingredients": [
{
"ingredients_name": "burger",
"ingredients_price": "200"
},
{
"ingredients_name": "pizza1",
"ingredients_price": "800"
}
]
}
]
}
]
}
How do I loop / foreach that array?
I guess there is a foreach inside a foreach, but I don't know how to do that.
In the manual of array_walk_recursive there is an example that might suit you.
http://php.net/manual/en/function.array-walk-recursive.php
$arr = json_decode($str, true); //$str is your json string
array_walk_recursive($arr, 'test_print');
function test_print($item, $key)
{
echo "[$key]: $item\n";
}
https://3v4l.org/dVUMS
If you only want to output some elements of the array you can create an array with the items you want to output and pass it on the function.
Then use in_array to see if it's a output or not.
https://3v4l.org/8ZvUS
Use this code:
<?php
$jsonData = '{
"success": "1",
"order_details": [
{
"item_order": 5,
"address": "155, Mani Nagar Society, Nana Varachha, Surat, Gujarat 395006, India",
"contact": "95303709",
"total_price": "3330.0",
"order_place": "18-05-25 06-07-20",
"preparing_date_time": "",
"preparing_status": "Deactivate",
"dispatched_date_time": "",
"dispatched_status": "Deactivate",
"delivered_date_time": "",
"delivered_status": "Deactivate",
"menu": [
{
"menu_name": "demo item",
"item_amt": "200",
"Ingredients": [
{
"ingredients_name": "burger",
"ingredients_price": "200"
},
{
"ingredients_name": "pizza1",
"ingredients_price": "800"
}
]
}
]
}
]
}';
$jsonDecode = json_decode($jsonData);
foreach ($jsonDecode->order_details as $orderDetail) {
echo "Item order: " . $orderDetail->item_order;
echo "<br>";
echo "Address: " . $orderDetail->address;
echo "<br>";
echo "Contact: " . $orderDetail->contact;
echo "<br>";
foreach ($orderDetail->menu as $menuItem) {
echo "Menu Name: " . $menuItem->menu_name;
echo "<br>";
echo "Item amt: " . $menuItem->item_amt;
echo "<br>";
foreach ($menuItem->Ingredients as $ingredientsItem) {
echo "Ingredients name: " . $ingredientsItem->ingredients_name;
echo "<br>";
echo "Ingredients price: " . $ingredientsItem->ingredients_price;
echo "<br>";
}
}
}
Output:
Item order: 5
Address: 155, Mani Nagar Society, Nana Varachha, Surat, Gujarat 395006, India
Contact: 95303709
Menu Name: demo item
Item amt: 200
Ingredient name: burger
Ingredient price: 200
Ingredient name: pizza1
Ingredient price: 800

How do i access this Json with PHP

am having issues trying to get contents of this json, am using php.
{"song":{"returncode":"200","returnmsg":"OK","title":"Despacito Ft. Justin Bieber","artist":"Luis Fonsi, Daddy Yankee","album":"","size":"9193600","url":"http://sami-server.info/Bita6/04.96/Billboard%20Hot%20100%20Singles/Billboard%20Hot%20100%20Singles/01.%20Luis%20Fonsi%2C%20Daddy%20Yankee%20-%20Despacito%20ft.%20Justin%20Bieber.mp3","time":"1499079781","date":"Jul 3, 2017","source":"","active":"1","albumart":"https://images-na.ssl-images-amazon.com/images/I/5150NxehQtL._AC_US160_.jpg","speed":"21","counter":"850850"}
this is my function, that returns the json
public function getSong($id) {
$song_url = 'http://databrainz.com/api/data_api_new.cgi?jsoncallback=&id='.$id.'&r=mpl&format=json&_=';
$api = Api::getSpotOn($song_url);
$song = $api->{'song'};
return $song;
}
I want to get all it content.
Thanks!
In the json example you provided a final '}' is missing and the json_decode will return Null without it as it's non a valid json.
But, since you have the getSong method the following should work:
$retObject = json_decode(getSong($songId));
$song = $retObject->song;
print_r($song);
echo 'returncode:'.$song->returncode.'<br/>';
echo 'returnmsg:'.$song->returnmsg.'<br/>';
echo 'title:'.$song->title.'<br/>';
echo 'artist:'.$song->artist.'<br/>';
echo 'album:'.$song->album.'<br/>';
echo 'size:'.$song->size.'<br/>';
echo 'url:'.$song->url.'<br/>';
echo 'time:'.$song->time.'<br/>';
echo 'date:'.$song->date.'<br/>';
echo 'source:'.$song->source.'<br/>';
echo 'active:'.$song->active.'<br/>';
echo 'albumart:'.$song->albumart.'<br/>';
echo 'speed:'.$song->speed.'<br/>';
echo 'counter:'.$song->counter.'<br/>';
try the following:
$result = json_decode(
'{
"song": {
"returncode": "200",
"returnmsg": "OK",
"title": "Despacito Ft. Justin Bieber",
"artist": "Luis Fonsi, Daddy Yankee",
"album": "",
"size": "9193600",
"url": "http://sami-server.info/Bita6/04.96/Billboard%20Hot%20100%20Singles/Billboard%20Hot%20100%20Singles/01.%20Luis%20Fonsi%2C%20Daddy%20Yankee%20-%20Despacito%20ft.%20Justin%20Bieber.mp3",
"time": "1499079781",
"date": "Jul 3, 2017",
"source": "",
"active": "1",
"albumart": "https://images-na.ssl-images-amazon.com/images/I/5150NxehQtL._AC_US160_.jpg",
"speed": "21",
"counter": "850850"
}
}'
);
var_dump($result);
echo $result->song->title;

JSON parsing of multidimensional JSON Object in PHP

I have the following JSON on a page
{
"users": [
{
"name": "John",
"age": "30",
},
{
"name": "Dave",
"age": "20",
},
...
]
}
I'm decoding it using $json = json_decode($data);. If I want a loop that print every name and age for each user how can I do that?
I'm tring to do something like the following code but it's not working
foreach($json->users->name as $key => $result){
$name = $result;
$age = $result->age;
echo $name;
echo $age;
echo "<br>";
}
What am I doing wrong? How could I achieve that?
You can do it like this:
$string = "{\"users\": [{\"name\": \"BA8842_530\",\"age\": \"0.0\"},{\"name\": \"BA8842_540\",\"age\": \"20\"}]}";
$json = json_decode($string, true);
foreach ($json['users'] as $key => $value) {
echo "Name: " . $value['name'] . "<br>";
echo "Age: " . $value['age'] . "<br>";
}
The output would be:
// Output
Name: BA8842_530
Age: 0.0
Name: BA8842_540
Age: 20
...
Hope this helps!
foreach($json->users as $row){
echo $row->name;
echo $row->age;
echo "<br>";
}

How to access multi-level json tree in PHP for database insertion

I am accessing an API where the JSON data is returned as below.
{
"name": "",
"count": 4,
"frequency": "",
"version": 3,
"newdata": true,
"lastrunstatus": "success",
"thisversionstatus": "success",
"thisversionrun": "",
"results": {
"collection": [{
"textlink": {
"href": "http://text1.com",
"text": "Text 1"
},
"index": 1,
"url": ""
}, {
"textlink": {
"href": "http://text2.com",
"text": "Text 2"
},
"index": 2,
"url": ""
}, {
"textlink": {
"href": "http://text3.com",
"text": "Text 3"
},
"index": 3,
"url": ""
}, {
"textlink": {
"href": "http://text4.com",
"text": "Text 4"
},
"index": 4,
"url": ""
}]
}}
As you can see the JSON tree returned has multi-step levels. I am wanting to be able to take some of the deeper levels, in PHP, and insert into a database.
Currently I am using this code to try and echo the data (once I am able to I can then work on inserting it to a database no problem)
<?php
$request = "API.REQUEST.NET";
$response = file_get_contents($request);
$results = json_decode($response, TRUE);
foreach($results as $item) {
echo $item->results[0]->collection[0]->textlink[0]->href;
echo "<br>";
echo $item->results->collection['href'];
echo "<br>";
echo $item->results->collection['text'];
}
?>
As you can see above I have tried several ways to access the deeper levels f data that are being displayed but with no avail.
I am currently getting errors of 'trying to get property of a non-object'. How is it possible to reach the data in this array?
try:
echo $results['results']['collection'][0]['textlink']['href'];
$obj = json_decode( $json, true ); foreach ( $obj['key'] as $key => $value ) { echo $value; }
foreach ($response['results']['collection'] as $textlink) {
$row = $textlink['textlink'];
echo $row['href'];
echo "<br>";
echo $row['text'];
echo "<br>";
}
you can do foreach like this, which loops only items in collection
I would suggest to do something like this (According to me, correct way to fetch results from API responses):
<?php
$request = "API.REQUEST.NET";
$response = file_get_contents($request);
$response = json_decode($response);
foreach($response->results->collection as $item) {
echo $item->textlink->href;
echo "<br>";
echo $item->textlink->text;
echo "<br>";
echo $item->index;
echo "<br>";
echo $item->url;
}
?>

Json decoding and displaying in php

So i've got a list with local weather details, http://api.openweathermap.org/data/2.5/weather?q=Schimmert,nl. And I want to display some of that in formation via php on my site, but can't really find out how JSON is something completely new for me.
And the only thing i managed to do right now is this: http://jeroenonline.biz/JSON/index.php. So this is a simple script:
$getData = file_get_contents( "http://api.openweathermap.org/data/2.5/weather?q=Schimmert,nl");
$decode = json_decode($getData);
echo "<pre>";
print_r($decode);
using the link
http://api.openweathermap.org/data/2.5/weather?q=Schimmert,nl
without the "." gives me a response
{
"message": "Error: Not found city",
"cod": "404"
}
<?php
$getData = file_get_contents( "http://api.openweathermap.org/data/2.5/weather?q=Schimmert,nl");
$decode = json_decode($getData);
// accessing it through object
echo $decode->message;
echo "<br/>";
echo $decode->cod;
// accessit via array
// set true the second parameter or the json_decode($encoded_data, TRUE)
// to give you array
$decode = json_decode($getData, TRUE);
echo "<br/>";
echo $decode['message'];
echo "<br/>";
echo $decode['cod'];
so when use the link with the "."
http://api.openweathermap.org/data/2.5/weather?q=Schimmert,nl.
gives a response of :
{
"coord": {
"lon": 5.83,
"lat": 50.91
},
"sys": {
"message": 0.0287,
"country": "Netherlands",
"sunrise": 1430884846,
"sunset": 1430939149
},
"weather": [
{
"id": 800,
"main": "Clear",
"description": "Sky is Clear",
"icon": "01n"
}
],
"base": "stations",
"main": {
"temp": 284.923,
"temp_min": 284.923,
"temp_max": 284.923,
"pressure": 1012.18,
"sea_level": 1023.56,
"grnd_level": 1012.18,
"humidity": 67
},
"wind": {
"speed": 6.06,
"deg": 219.002
},
"clouds": {
"all": 0
},
"dt": 1430875602,
"id": 0,
"name": "Nuth",
"cod": 200
}
to show the the result
// sample to access coord
echo $decode->coord->lon;
echo $decode->coord->lat;
// sample to access sys
echo $decode->sys->message;
echo $decode->sys->country;
// sample to access weather
echo $decode->weather[0]->id;
echo $decode->weather[0]->main;
echo $decode->weather[0]->description;
// sample to access main
echo $decode->main->temp;
echo $decode->main->temp_min;
// sample to access wind
echo $decode->wind->speed;
// sample to access clouds
echo $decode->clouds->all;
echo $decode->id;
echo $decode->name;
echo $decode->cod;
If you want to use the JSON as an array instead, you just have to pass true as the second paramenter for json_decode.
$getData = file_get_contents( "http://api.openweathermap.org/data/2.5/weather?q=Schimmert,nl");
$decode = json_decode($getData, true);
echo "<pre>";
print_r($decode);
this API http://api.openweathermap.org/data/2.5/weather?q=Schimmert,nl. get some data like this
{
"coord": {
"lon": 5.83,
"lat": 50.91
},
"sys": {
"message": 0.039,
"country": "Netherlands",
"sunrise": 1430884846,
"sunset": 1430939149
},
"weather": [
{
"id": 800,
"main": "Clear",
"description": "Sky is Clear",
"icon": "01n"
}
],
"base": "stations",
"main": {
"temp": 284.923,
"temp_min": 284.923,
"temp_max": 284.923,
"pressure": 1012.18,
"sea_level": 1023.56,
"grnd_level": 1012.18,
"humidity": 67
},
"wind": {
"speed": 6.06,
"deg": 219.002
},
"clouds": {
"all": 0
},
"dt": 1430875157,
"id": 2749752,
"name": "Nuth",
"cod": 200
}
try this
<?php
$getData = file_get_contents("http://api.openweathermap.org/data/2.5/weather?q=Schimmert,nl."); // get your json data
$decode = json_decode($getData); // decode it to be an object
// echo "<pre>";
// print_r($decode);
// you can get the data with
echo "Country : " . $decode->sys->country; echo '<br>';
for($i=0;$i<count($decode->weather);$i++){
echo "ID : " . $decode->weather[0]->id; echo '<br>';
echo "Weather : " . $decode->weather[0]->main; echo '<br>';
echo "Description : " . $decode->weather[0]->description; echo '<br>';
echo "Icon : " . $decode->weather[0]->icon; echo '<br>';
}
echo "Temperature : " . $decode->main->temp; echo '<br>';
echo "Temp Min : " . $decode->main->temp_min; echo '<br>';
echo "Temp Max : " . $decode->main->temp_max; echo '<br>';
echo "Preassure : " . $decode->main->pressure; echo '<br>';
echo "Sea Level : " . $decode->main->sea_level; echo '<br>';
echo "Ground Level : " . $decode->main->grnd_level; echo '<br>';
echo "Humidity : " . $decode->main->humidity; echo '<br>';
echo "Wind Speed : " . $decode->wind->speed; echo '<br>';
echo "Wind Degrees : " . $decode->wind->deg; echo '<br>';
echo "Cloud : " . $decode->clouds->all; echo '<br>';
?>

Categories