I have a json file that I want to read with PHP
http://rh.ernestek.cz.cc/webeast/static.txt
I wanted to extract the "id" and the "key"
I wanted to loop through the id and key so that I can produce a table like this:
ID Key
1 9d07d681e0c1e294264724f7726e6f6f29
3 9cd1e3a4a04b5208862c3140046f73b515
...
I tried to extract the first id and key out using the following code but no luck:
<?php
$json = file_get_contents('static.txt');
$json_decoded = json_decode($json);
echo "ID: ".$json_decoded->static->1->id."<br />";
echo "Key: ".$json_decoded->static->1->key."<br />";
?>
Is there anything I an wrong?
Any ideas?
Thanks!
Decode the json as an array (pass true as second parameter), and loop over the array like so
<?php
$json = file_get_contents('static.txt');
$json_decoded = json_decode($json, true);
foreach ($json_decoded['static'] as $item) {
echo 'ID: ', $item['id'], '<br/>';
echo 'Key: ', $item['key'], '<br/>';
}
By using true in json_decode() it will convert all objects to array:
$json = file_get_contents("http://rh.ernestek.cz.cc/webeast/static.txt");
$json_decoded = json_decode($json, true); // return array
$table = array();
foreach($json_decoded["static"] as $array){
$table[$array["id"]] = $array["key"];
}
//creating the table for output
$output = '<table border="1"><tr><td>ID</td><td>Key</td></tr>';
foreach($table as $id => $key){
$output .= "<tr><td>$id</td><td>$key</td></tr>";
}
$output .= '</table>';
echo $output;
Related
I have a PHP code that converts a JSON into an array of two elements.
{"object":"card","id":"card_1"}
But when I try to print the both, the first returns the value and the second only the boolean.
echo 'id = ' . $response["id"];
echo 'object = ' .$response["object"];
Getting this:
id = true
object = card
What is wrong?
It seems, that you use json_decode to convert your JSON data to an array. Use next basic example to get your expected data:
<?php
// Input
$json = '{"object":"card","id":"card_1"}';
$array = json_decode($json, true);
// Specific items
echo 'id = '.$array["id"].'<br>';
echo 'object = '.$array["object"].'<br>';
// All items
foreach($array as $key => $value) {
echo $key.": ".$value."<br>";
}
?>
Could you please provide the code you use to convert this JSON into an array ?
This works fine:
$jsonObject = '{"object":"card","id":"card_1"}';
$decodedObject = json_decode($jsonObject);
$object = $decodedObject->object;
$id = $decodedObject->id;
echo "Object: {$object}, ID: {$id}";
I'm using iTunes RSS generator to get HOT tracks, now I'm using following way to parse JSON:
<?php
$json_string = 'https://rss.itunes.apple.com/api/v1/in/apple-music/hot-tracks/all/10/explicit.json';
$jsondata = file_get_contents($json_string);
$obj = json_decode($jsondata,true);
$cltn = $obj['feed']['results'][0]['collectionName'];
echo $cltn;
?>
Now, as we know that It'll return only 1 collectionName.
JSON request is returning 10 results. How can I get them all using foreach loop? I've used several ways but no success.
Since you didn't give the output of the array I assume the [0] index is what needs to be iterated.
You need to foreach the $obj['feed']['results'] by doing:
Foreach($obj['feed']['results'] as $cltn){
Echo $cltn['collectionName'];
}
Foreach over the results:
foreach ($obj['feed']['results'] as $result) {
echo $result['collectionName'] . '<br>' . PHP_EOL;
}
Based on the code you provided you can iterate the results to get all possible information from the artist/track list, for example:
$json_string = 'https://rss.itunes.apple.com/api/v1/in/apple-music/hot-tracks/all/10/explicit.json';
$jsondata = file_get_contents($json_string);
$obj = json_decode($jsondata,true);
$cltn = $obj['feed']['results'];
function test_print($item, $key)
{
echo "<strong>".$key."</strong>: ".$item."<br>";
}
foreach($cltn as $key => $c) {
echo "Result No ".($key+1)."<br>";
array_walk_recursive($c, 'test_print');
}
in case you only want to show artistName and collectionName you can slightly modify the above example:
$json_string = 'https://rss.itunes.apple.com/api/v1/in/apple-music/hot-tracks/all/10/explicit.json';
$jsondata = file_get_contents($json_string);
$obj = json_decode($jsondata,true);
$cltn = $obj['feed']['results'];
foreach($cltn as $c) {
echo $c['artistName'].": ".$c['collectionName']."<br>";
}
You can try all the above in PHP Fiddle
Try like this way with foreach() to iterate your array in key=>value manner as you've decoded the json as an array not an object in php.
<?php
$json_string = 'https://rss.itunes.apple.com/api/v1/in/apple-music/hot-tracks/all/10/explicit.json';
$jsondata = file_get_contents($json_string);
$array = json_decode($jsondata,true);
# printing resulted array just for debugging purpose
print '<pre>';
print_r($array);
print '</pre>';
foreach($array['feed']['results'] as $key=>$value){
echo $value['collectionName'].'<br/>';
}
?>
So I would like to create just one loop to parse the json data i have. I can successfully parse it in 2 foreach loops however when trying to combine in one loop using $key => $value the $key returns nothing when called. How can I successfully take the 2 foreach loops I have here and combine them into one?
$contents = file_get_contents($url);
$results = json_decode($contents, true);
$jsonList = $results['genres'];
foreach($jsonList as $key) {
$GenreID = $key['id'].'<br>';
echo $GenreID;
}
foreach($jsonList as $key => $value) {
$GenreName = $value['name'].'<br><br>';
echo $GenreName;
}
The json data is as follows:
{"genres":[{"id":28,"name":"Action"},{"id":12,"name":"Adventure"},{"id":16,"name":"Animation"},{"id":35,"name":"Comedy"},{"id":80,"name":"Crime"},{"id":99,"name":"Documentary"},{"id":18,"name":"Drama"},{"id":10751,"name":"Family"},{"id":14,"name":"Fantasy"},{"id":36,"name":"History"},{"id":27,"name":"Horror"},{"id":10402,"name":"Music"},{"id":9648,"name":"Mystery"},{"id":10749,"name":"Romance"},{"id":878,"name":"Science Fiction"},{"id":10770,"name":"TV Movie"},{"id":53,"name":"Thriller"},{"id":10752,"name":"War"},{"id":37,"name":"Western"}]}
You can still use $key as an index when also extracting the $value.
However note that you shouldn't be assigning the line breaks to your variables, and should instead consider them part of the view by echoing them out independently:
$contents = file_get_contents($url);
$results = json_decode($contents, true);
$jsonList = $results['genres'];
foreach($jsonList as $key => $value) {
$GenreID = $key['id']; // Depending on structure, you may need $value['id'];
$GenreName = $value['name'];
echo $GenreID . '<br>';
echo $GenreName . '<br><br>';
}
Your single loop below here.
foreach($jsonList as $key)
{
$GenreID = $key['id'].'<br>';
echo $GenreID;
$GenreName = $value['name'].'<br><br>';
echo $GenreName;
}
$key is a assosative array.Therefore it had some index.So you can use this index in single loop.
It seems you get confused over your data structure. Seeing the json, the resulting "$jsonlist" supposed to contain array with id and value as keys.
You can iterate over it and extract the the appropriate key.
Myabe something like this:
foreach($jsonlist as $value) {
echo "id: " . $value['id'] . "\n";
echo "name: " . $value['name'] . "\n";
}
extra bonus, if you want to create 1 level array from your json based on id with the name you could try array reduce using anon function like this:
$jsonlist = array_reduce($jsonlist, function($result, $item){
$result[$item['id']] = $item['name'];
return $result;
}, []);
extra neat for transformation of static structure data.
{"2b44928ae11fb9384c4cf38708677c48":{
"id":"115",
"qty":3,
"option":"{\"color\":{\"title\":\"Color\",
\"value\":\"\"
}
}",
"price":150,
"name":"Nightwear",
"shipping":"5",
"tax":3,
"image":"http:\/\/localhost\/plus\/uploads\/product_image\/product_115_1_thumb.jpg",
"coupon":"",
"rowid":"2b44928ae11fb9384c4cf38708677c48",
"subtotal":450
}
}
Hello everyone,
This is my array and I want to echo value of only "id" i.e. I want to get value as '115' of key- "id". Please guide me how to make a foreach for this one? I have tried lots of variations but none worked :(
TIA :)
UPDATE-
I have tried this but did not get any result:
foreach($res as $k=>$t)
{
echo $t["product_details"]["id"];
}
Before you can use the JSON as an array you need to convert it first. use json_decode() for that.
<?php
$json='{"2b44928ae11fb9384c4cf38708677c48":{"id":"115","qty":3,"option":"{\"color\":{\"title\":\"Color\",\"value\":\"\"}}","price":150,"name":"Nightwear","shipping":"5","tax":3,"image":"http:\/\/localhost\/plus\/uploads\/product_image\/product_115_1_thumb.jpg","coupon":"","rowid":"2b44928ae11fb9384c4cf38708677c48","subtotal":450}}';
$array = json_decode($json, true);
foreach($array as $key=>$value){
echo $value['id'];
}
?>
Assuming you have an array of objects like you provided in your post, I have put your object in an array for testing
<?php
$json = '[{"2b44928ae11fb9384c4cf38708677c48":{"id":"115","qty":3,"option":"{\"color\":{\"title\":\"Color\",\"value\":\"\"}}","price":150,"name":"Nightwear","shipping":"5","tax":3,"image":"http:\/\/localhost\/plus\/uploads\/product_image\/product_115_1_thumb.jpg","coupon":"","rowid":"2b44928ae11fb9384c4cf38708677c48","subtotal":450}},'.
'{"2b44928ae11fb9384c4cf38708677c48":{"id":"116","qty":3,"option":"{\"color\":{\"title\":\"Color\",\"value\":\"\"}}","price":150,"name":"Nightwear","shipping":"5","tax":3,"image":"http:\/\/localhost\/plus\/uploads\/product_image\/product_115_1_thumb.jpg","coupon":"","rowid":"2b44928ae11fb9384c4cf38708677c48","subtotal":450}}]';
$json = json_decode($json);
foreach ($json as $object){
$propsArray = get_object_vars($object);
reset($propsArray);
echo $object->{key($propsArray)}->id . "<br>\n";
}
exit;
this outputs
115
116
try a live demo (https://eval.in/836364)
$json='{"2b44928ae11fb9384c4cf38708677c48":{"id":"115","qty":3,"option":"{\"color\":{\"title\":\"Color\",\"value\":\"\"}}","price":150,"name":"Nightwear","shipping":"5","tax":3,"image":"http:\/\/localhost\/plus\/uploads\/product_image\/product_115_1_thumb.jpg","coupon":"","rowid":"2b44928ae11fb9384c4cf38708677c48","subtotal":450}}';
$array = json_decode($json, true); // convert json string to array
$result = array_column($array, 'id'); // find matching array key and return values in array
foreach ($result as $value) { // echo each value with foreach loop
echo $id . '<br>';
}
i have the following JSON:
{"Switches":["Auswahl1","Auswahl2","Auswahl3"],"Check_MK":["Auswahl1","Auswahl2","Auswahl3"],"Testgroup":["Auswahl1","Auswahl2","Auswahl3"],"Printer":["Auswahl1","Auswahl2","Auswahl3"],"CAD":["Auswahl1","Auswahl2","Auswahl3"]}
How do i loop each object while using PHP?
My thoughts were the following:
<?php
$jsonfile = file_get_contents('tags.json');
echo $jsonfile . "<br><br>";
$decode = json_decode($jsonfile);
foreach($decode as $key => $value) {
echo $key . $value;
}
?>
Doesn't work..... Also
echo $decode[1];
and
echo $decode[1][1];
doesn't work..
You need to add a second parameter to json_decode()
This parameter returns associative array instead of existing object (if existing).
$decode = json_decode($jsonfile, TRUE);
This will convert your JSON decoded data into associative array.
$jsonfile = file_get_contents('tags.json');
echo $jsonfile . "<br><br>";
$decode = json_decode($jsonfile);
now $decode is equivalent to:
$decode = new stdClass();
$decode->Switches = array();
$decode->Switches[] = "Auswahl1";
$decode->Switches[] = "Auswahl2";
$decode->Switches[] = "Auswahl3";
$decode->Check_MK = array();
...