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

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);
}

Related

Foreach json output and store in variables

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'] ;
}

Turn json file into php array to select random name from the array

Problem is as follows:
I'm exporting a list of names and values(repCode) attached to each name from excel into a json file.
I then want to convert the json file into a php array so that I can have a piece of code that will select a random name from the php array and display the random name(and value(repCode) attached to the name).
I've tried many options so far but I keep running into problems that I'm struggling to find a solution for. One example would be:
<?php
$jsondata = file_get_contents("Names.json");
$json = json_decode($jsondata, true);
$output = '<ul>';
foreach($json['Reps']as $reps){
$output .='<h4>' .$reps['Client']."<h4>";
$output .= "<li>".$reps['Code']."</li>";
}
$output .= "</ul>";
$element = $output[mt_rand(0, count($output) - 1)];
echo $element;
?>
That doesn't work.
json File as follow: "Names.json"
{
"Reps": [
{"Client":"Jack",
"repCode":"tt1790861"},
{"Client":"James",
"repCode":"tt1790862"},
{"Client":"Sam",
"repCode":"tt1790863"},
{"Client":"Hendry",
"repCode":"tt1790864"},
{"Client":"Samone",
"repCode":"tt1790865"},
{"Client":"Judy",
"repCode":"tt179086"},
{"Client":"Jake",
"repCode":"tt1790867"},
{"Client":"Amy",
"repCode":"tt1790868"},
{"Client":"Brandon",
"repCode":"tt1790869"},
{"Client":"Blake",
"repCode":"tt17908610"},
{"Client":"Rick",
"repCode":"tt17908611"},
{"Client":"Morty",
"repCode":"tt17908612"}
]
}
And then below is some php code:
<?php
// JSON string
$someJSON = "Names.json";
// Convert JSON string to Array
$someArray = json_decode($someJSON, true);
print_r($someArray); // Dump all data of the Array
echo $someArray[0]["Client"]; // Access Array data
?>
I'm getting no result when I echo out the json file.
So I can't even get to the part where I want to use the json file that's been converted into a php array so I can have code to select a random name + associated rep code and display it.
Any help would be appreciated.
In your first example you're trying to use $output as an array, it's not. Also, you're not accessing the keys of $element:
$element = $json['Reps'][mt_rand(0, count($json['Reps']) - 1)];
//or
$element = $json['Reps'][array_rand($json['Reps'])];
echo $element['Client'];
echo $element['repCode'];
For your second example, you're not actually loading the JSON file and then you forget the Reps key:
$someJSON = file_get_contents("Names.json");
$someArray = json_decode($someJSON, true);
print_r($someArray);
echo $someArray["Reps"][0]["Client"];
//or random
echo $someArray["Reps"][array_rand($someArray["Reps"])]["Client"];

How to take out int value from JSON object?

I'm working with Laravel 5 right now and I have the following problem. I've got response from DB query:
[{"id":1}]
and I want to take out 1 as int or string. Any ideas?
I've tried to solve this like follows:
$json = (DB query);
$data = json_decode($json);
$final = $data[0]->id;
and response is :
json_decode() expects parameter 1 to be string, array given
This is all you need.
$response = json_decode($response); // Decode the JSON
$string = $response[0]->id; // Save the value of id var
As you say, the string you have is in JSON format, so you need to use json_decode to access it in PHP.
The square brackets refer to an array, and the braces refer to an object within that array, so what you're looking for is the id value of the first element (i.e. element 0) in the array.
<?php
$json = '[{"id":1}]';
$data = json_decode($json);
echo $data[0]->id;
// 1
Try this
$json_array = '[{"id":1}]';
$data = json_decode($json_array);
print_r($data); // To display the result array
You just need to decode it, if I'm not misunderstanding your questions.
$json = '[{"id":1}]';
$decodedObject = json_decode($json);
Then you can loop through the aray and do something with your data:
foreach($decodedObject as $key => $value) {
$id = $value->id;
}
If you're using Laravel, though, why not use Eloquent models?

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.

GET info from external Array/API/URL using PHP

I have the url http://pubapi.cryptsy.com/api.php?method=singleorderdata&marketid=132 which leads to an array.
I want to get the value of the first 'sellorders' which in this case is: 0.00000048 and store it in the variable $sellorderprice.
Can anyone help?
Thanks.
Just access the url contents thru file_get_contents. Your page actually return a JSON string, to get those values into meaningful data, decode it thru json_decode, after that access the data needed accordingly:
$url = 'http://pubapi.cryptsy.com/api.php?method=singleorderdata&marketid=132';
$data = json_decode(file_get_contents($url), true);
$sellorderprice = $data['return']['DOGE']['sellorders'][0]['price'];
echo $sellorderprice;
That code actually points directly to index zero 0 which gets the first price. If you need to get all items an just simply echo them all you need to iterate all items thru foreach:
foreach($data['return']['DOGE']['sellorders'] as $sellorders) {
echo $sellorders['price'], '<br/>';
}
Its simple, you just have to decode json like this:
$json = file_get_contents("http://pubapi.cryptsy.com/api.php?method=singleorderdata&marketid=132");
$arr = json_decode($json, true);
$sellorderprice = $arr['return']['DOGE']['sellorders'][0]['price'];

Categories