Foreach json output and store in variables - php

I am trying to foreach the result from a json code.
I have checked the json result at jsonlint and it's validated.
I do this:
$result = curl_exec($curl);
if(!$result){die("Connection Failure");}
curl_close($curl);
Then when i do echo $result this is the result:
{"vat":{"640252":{"name":"0%","percentage":"0.00","invoice_type":"2","vat_code":"5B2","available":"1"},"640258":{"name":"0%","percentage":"0.00","invoice_type":"1","vat_code":"1E1","available":"1"},"640256":{"name":"21%","percentage":"21.00","invoice_type":"1","vat_code":"1A2","available":"1"}}}
when i do this it does show the name of vat code 640252:
$result2 = json_decode($result, true);
echo $result2['vat']['640252']['name'];
But i cannot go through the json with a foreach. To start would like to make a variable with the id (like 640252) and one with the percentage, and echo them in the foreach.
I have tried a lot of things from Stackoverflow but all the json output seems to look different from the output that i have.
I hope that someone can help me in the right direction.

The reson is, that the vat is a key with a value array after decoding the json string. Just iterate the vat property as in the following example.
$data = json_decode($result, true);
foreach ($data['vat'] as $id => $item) {
echo "<pre>";
var_dump($id, $item);
echo "</pre>";
}
Hope that helps.

<?php
$json = '... lots of JSON here ...';
$arr = json_decode($json, true);
foreach ($arr['vat'] as $id => $item) {
echo "$id -> {$item['name']}\n";
}
Using your JSON as an example, this is the output that I get:
640252 -> 0%
640258 -> 0%
640256 -> 21%
If you don't need the ID (e.g. 640252) you can just do:
foreach ($arr['vat'] as $item) {

Firstly I would suggest to format your json to be readable for you. Personally I use https://jsonlint.com/ to validate my json data.
If we do that, we can see that vat is a json object which haves those 640252, 640258 etc as direct child's.
Decoding with second parameter as true, will decode as associative array. Looping over the vat properties would be:
foreach($result2['vat'] as $id => $val) {
echo 'Id is:'. $id;
echo 'name is '. $val['name'] ;
echo 'percentage is '. $val['percentage'] ;
}

Related

How do I target nested JSON objects in php, and echo them?

Okay, so I think you get what I wanna do by just watching the code.
//Get JSON text file (Steam API)
$json = file_get_contents('http://store.steampowered.com/api/appdetails?appids=57690');
//Decode JSON
$game_json = json_decode($json, true);
//Target game name and echo it
echo $game_json['name'];
The JSON itself comes in this order (unstructured, very sorry):
{"57690":{"success":true,"data":{"type":"game","name":"Tropico 4: Steam Special Edition"
So my target is ""name":"Tropico 4: Steam Special Edition"", which is what I want to echo on my page. I'm not sure if it helps, but "name": appears once, is something like [0] needed in my code to target the first? Is the nesting what's stopping me here, or is the $game_json['name']; an incorrect way of targeting?
ANY tips and/or help will be much appreciated. Thanks.
In the future, use print_r($game_json) to check the array structure.
<?php
$json = file_get_contents('http://store.steampowered.com/api/appdetails?appids=57690');
$game_json = json_decode($json, true);
echo $game_json['57690']['data']['name'];
//Tropico 4: Steam Special Edition
echo $game_json['57690']['data']['required_age'];
//0
//etc...
<?php
//This is your json string
$string = {"57690":{"success":true,"data":{"type":"game","name":"Tropico 4: Steam Special Edition"...
//Turn JSON string into object
$data = json_decode($string);
//Turn your object into an array (easier to work with in this case)
$data = (Array)$data;
//Get name of item with "57690" key
$name = $data["57690"]->data->name;
//Echo the name
echo($name);
//You can also echo out all names of all items like this:
foreach($data as $key => $item)
{
echo($item->data->name);
}

JSON decode Array and insert in DB

I have some issue with a decoded Json object sended to a php file. I have tried some different format like this
{"2":"{Costo=13, ID=9, Durata_m=25, Descrizione=Servizio 9}","1":"{Costo=7, ID=8, Durata_m=20, Descrizione=Servizio 8}"}
or this.
[{"Costo":"7.5","ID":"3","Durata_m":"30","Descrizione":"Barba Rasoio"},{"Costo":"4.5","ID":"4","Durata_m":"20","Descrizione":"Barba Macchinetta"}]
In order the first, any suggestions helps me, then i have converted previous string using GSON, however php doesn't decode.
This is my php:
//Receive JSON
$JSON_Android = $_POST["JSON"];
//Decode Json
$data = json_decode($JSON_Android, true);
foreach ($data['servizi'] as $key => $value)
{ echo "Key: $key; Value: $value<br />\n";
}
How can I access single elements of array? What I'm doing wrong? Thanks in advance
I think you should check the content in this way
//Receive JSON
$JSON_Android = $_POST["JSON"];
//Decode Json
$data = json_decode($JSON_Android, true);
foreach ($data as $key => $value) {
echo "FROM PHP: " . $value;
echo "Test : " .$value['ID'];
}
your elements of {Costo=7, ID=8, Durata_m=20, Descrizione=Servizio 8}
are not properly formated as an array element. That is a pure string and not an array value.
This is a json object with 1 element of array:
{
"1": {
"Costo": 7,
"ID": 8,
"Durata_m": 20
}
}
The Inside are json objects. Therefore your json string was not properly formated to operate with that logic. What you had was an element of a string. That is the reason why it was a valid json (passing jsonlint) but was not the correct one that you wanted to use.
UPDATE
Because this format is fix, I have a non-elegant way:
//Receive JSON
$JSON_Android = $_POST["JSON"];
//Decode Json
$data = json_decode($JSON_Android, true);
foreach ($data as $key => $value) {
//to separate each element
$newArray = explode(',',$value);
$newItem = explode('=', $newArray[1]);
echo "ID". $newItem[1];
}
That would be the dirty way to do it ONLY IF THE PLACEMENT OF DATA IS FIX. (ie the second element of the first explode is always ID.
I will leave it to someone else to make the suggested code better. I would recommend more to ensure that the json you are receive is proper because as I explained, it is incorrectly formated and as an api developer, you want an adaptive way for any given client to use the data efficiently.

how do i split my result using json

im using a text messaging service provider to send and receive messages. the following is the code that works successfully to retrieve messages from the texting server and displays on my website
the problem is when it displays this data its in one big chunk,sorry im not a great programmer therfore I want to split each text messages up by a few spaces,
please could you help me write up a json script that would allow me to split up my result, cheers
You need to decode the JSON from the string into an array or object, using json_decode() it has a second parameter that's bool (When TRUE, returned objects will be converted into associative arrays.)
So something like (Object):
$responseObj = json_decode($response);
foreach ( $responseObj as $key => $value )
echo "$key = $value<br>";
So something like (Array):
$responseArray = json_decode($response, true);
foreach ( $responseArray as $key => $value )
echo "$key = $value<br>";
first of all do use json_decode function of php then it will come up in an array where at "messages" index you can find your all messages. After that you have to run for each loop then you can get your code working.
$arr = json_decode($response, true);
foreach($arr['messages'] as $message){
echo $message['message'];
}
<?php
$response = json_decode($response);
foreach($response['messages'] as $msgObj) {
print $msgObj->message . "<br/><br/>";
}
?>

How to loop through this json decoded data in PHP?

I've have this list of products in JSON that needs to be decoded:
"[{"productId":"epIJp9","name":"Product A","amount":"5","identifier":"242"},{"productId":"a93fHL","name":"Product B","amount":"2","identifier":"985"}]"
After I decode it in PHP with json_decode(), I have no idea what kind of structure the output is. I assumed that it would be an array, but after I ask for count() it says its "0". How can I loop through this data so that I get the attributes of each product on the list.
Thanks!
To convert json to an array use
json_decode($json, true);
You can use json_decode() It will convert your json into array.
e.g,
$json_array = json_decode($your_json_data); // convert to object array
$json_array = json_decode($your_json_data, true); // convert to array
Then you can loop array variable like,
foreach($json_array as $json){
echo $json['key']; // you can access your key value like this if result is array
echo $json->key; // you can access your key value like this if result is object
}
Try like following codes:
$json_string = '[{"productId":"epIJp9","name":"Product A","amount":"5","identifier":"242"},{"productId":"a93fHL","name":"Product B","amount":"2","identifier":"985"}]';
$array = json_decode($json_string);
foreach ($array as $value)
{
echo $value->productId; // epIJp9
echo $value->name; // Product A
}
Get Count
echo count($array); // 2
Did you check the manual ?
http://www.php.net/manual/en/function.json-decode.php
Or just find some duplicates ?
How to convert JSON string to array
Use GOOGLE.
json_decode($json, true);
Second parameter. If it is true, it will return array.
You can try the code at php fiddle online, works for me
$list = '[{"productId":"epIJp9","name":"Product A","amount":"5","identifier":"242"},{"productId":"a93fHL","name":"Product B","amount":"2","identifier":"985"}]';
$decoded_list = json_decode($list);
echo count($decoded_list);
print_r($decoded_list);

Iterate over a JSON response and get results into variables

I am trying to build a simple script that I can pass in a list of Twitter username and it will then access the Twitter API and returns a list of details for the user's that I requested.
Below is what I have so far, it returns a JSON response with all the data for the 3 user's that I sent in the URL.
I need to figure out how to access each of these items, I plan to save them to a database so I need to be able to access the returned items as a variable. Also the number of users/results in the JSON will be different each time depending on how many names I request so I need to somehow iterate over this JSON response.
Can anyone help me?
$json = file_get_contents('http://api.twitter.com/1/users/lookup.json?screen_name=fishriver,metinogtem,friendproject');
$obj = json_decode($json);
echo '<pre>';
print_r($obj);
echo '</pre>';
Iterating is easy:
foreach ($obj as $varName => $varValue)
{
// ...
}
Use foreach to iterate over the JSON object.
$json = file_get_contents('http://api.twitter.com/1/users/lookup.json?screen_name=fishriver,metinogtem,friendproject');
$obj = json_decode($json);
echo '<pre>';
foreach($obj as $index => $user) {
echo $user->screen_name."<br>";
// insert into database here
}
echo '</pre>';

Categories