creating one loop for parsing json data - php

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.

Related

Retrieve first element of JSON with php [duplicate]

This question already has answers here:
Parsing JSON in PHP
(2 answers)
Closed 5 years ago.
I got a JSON from a web site in the raw format:
{"A_B":{"id":7,"last":"0.00000038"},"A_C":{"id":8,"last":"0.00001938"}, ... }
How do I get the A_B and A_C??? I do not know what A_B and A_C could be.
Try the following.
$json = file_get_contents("your json data");
$arr = json_decode($json, true);
foreach ($arr as $key=>$val) {
var_dump($key);
}
Finally, var_dump($key) displays A_B and A_C.
Suppose you have that raw json in some variable, say $yourJson
First, parse your json. $parsedJson = json_decode($yourJson, true)
Then run a foreach loop and stop after 2 iterations, You will (hopefully) get the right key-value pair.
$i = 0;
$extractedValues = [];
foreach ($parsedJson as $key => $value) {
$extractedValues[$key] = $value; $i++;
if ($i === 2) {
break;
}
}
Now, $extractedValues contains only two elements found from the first two iterations.
$data = json_decode("Your json variable");
foreach($data as $value){
echo $value; // here you receive your desire value.
}
Try this:
$json = '{"A_B":{"id":7,"last":"0.00000038"},"A_C":{"id":8,"last":"0.00001938"}}';
$dataArray = json_decode($json, true);
$arrayKeys = array_keys($dataArray); // in your case A_B and A_C
and if you want to get their values then:
foreach($dataArray as $data) {
foreach($data as $key => $value) {
echo $key . ": " . $value . PHP_EOL;
}
}
var $jsonObj = json_decode('{"A_B":{"id":7,"last":"0.00000038"}}')
print $jsonObj->{'A_B'}

Printing json data

I have this json "https://www.decodethis.com/webservices/decodes/1Fmzu64p5yzb76700/aYcBzLfMCRs_JScq_sZt/0.json"
and I decode it with $data = json_decode($json, true);
But when I try to print the Vehicle part foreach($data['vehicle'][0] as $p)
{echo $p;}
the system prints"Invalid argument supplied for foreach()" and "Undefined index".
I'm a newbie, so forgive me.
Edit:This worked very well foreach ($data['decode']['vehicle'][0] as $p) echo $p;, but now I wonder if I can know the key or index of the element $p on every loop, as example "body>driveline>engine>id"...
the path is like these;
foreach ($data['decode']['vehicle'][0] as $p) echo $p;
You may want to to use:
$json = file_get_contents("https://www.decodethis.com/webservices/decodes/1Fmzu64p5yzb76700/aYcBzLfMCRs_JScq_sZt/0.json");
$obj = json_decode($json, true);
foreach($obj["decode"]["vehicle"] as $vehicle )
{
echo $vehicle['body'];
echo $vehicle['engine'];
# etc...
}
For accessing output in json file there is decode as root key. So first access decode key then after use vehicle information.
Below is code for that:
$data = json_decode($json, true);
$json = $data["decode"]["vehicle"][0];
foreach($json->entries as $row) {
foreach($row as $key => $val) {
echo $key . ': ' . $val;
echo '<br>';
}
}

PHP - Getting array element from Json

I'm working with the JSON here: http://steamcommunity.com/id/mitch8910/inventory/json/730/2/
I'm trying to get the tags[{"name":""}] part of it. For example, I would want the 'container', from '"name":"Container"'
This is my code here:
$data = file_get_contents('http://steamcommunity.com/id/mitch8910/inventory/json/730/2/');
$json = json_decode($data);
foreach ($json->rgDescriptions as $mydata)
{
echo $mydata->tags[1];
}
tags[] is an array, though I did tags[1], I don't awlays want the '1'th element because the position of "name" could change in the array for different elements, I just did this to test, but I got an error. I have tried multiple ways with multiple errors, that why I'm not posting all the error code.
The simplest way may be to do an extra loop to grab all the name elements:
$data = file_get_contents('http://steamcommunity.com/id/mitch8910/inventory/json/730/2/');
$json = json_decode($data);
foreach ($json->rgDescriptions as $mydata)
{
foreach($mydata->tags as $tag) {
echo $tag->name;
}
}
or to get the first name of each tag group:
foreach ($json->rgDescriptions as $mydata)
{
echo $mydata->tags[0]->name;
}
I updated the whole answer:
$json = json_decode($data, true);
if (isset($json['rgDescriptions']) && is_array($json['rgDescriptions'])){
foreach ($json['rgDescriptions'] as $array_no => $value) {
if (isset($json['rgDescriptions'][$array_no]['tags'])){
echo "{$array_no}::::";
foreach ($json['rgDescriptions'][$array_no]['tags'] as $k => $value) {
if (isset($json['rgDescriptions'][$array_no]['tags'][$k]['name'])){
echo "{$json['rgDescriptions'][$array_no]['tags'][$k]['name']},";
}
}
echo "<br />";
}
}
}

How to fetch URL variable array using $_REQUEST['variable name']

I am using a URL to fetch data stored/shown within URL. I get all the value of variable using $_REQUEST['v_name'] but if there is a array in URL how can i retrieve that value.
For Example:
WWW.example.com/rooms?&hid=213421&type=E
I got the value hid and type using
$hid=$_REQUEST['hid'];
but in URL like:
WWW.example.com/rooms?&rooms=2&rooms[0].adults=2&rooms[0].children=0&rooms[1].adults=2&rooms[1].children=0
how can i retrieve value of adults and children in each room.
please help.
Thanks in Advance
You could also try something like this, since most of your original $_REQUEST isn't really an array (because of the .s in between each key/value pair):
<?php
$original_string = rawurldecode($_SERVER["QUERY_STRING"]);
$original_string_split = preg_split('/&/', $original_string);
$rooms = array();
foreach ($original_string_split as $split_one) {
$splits_two[] = preg_split('/\./', $split_one);
}
foreach ($splits_two as $split_two) {
if (isset($split_two[0]) && isset($split_two[1])) {
$split_three = preg_split('/=/', $split_two[1]);
if (isset($split_three[0]) && isset($split_three[1])) {
$rooms[$split_two[0]][$split_three[0]] = $split_three[1];
}
}
}
// Print the output if you want:
print '<pre>' . print_r($rooms, 1) . '</pre>';
$valuse = $_GET;
foreach ($valuse as $key=>$value)
{
echo $key .'='. $value. '<br/>';
}

Retrieving array keys from JSON input

I have this array:
$json = json_decode('
{"entries":[
{"id": "29","name":"John", "age":"36"},
{"id": "30","name":"Jack", "age":"23"}
]}
');
and I am looking for a PHP "for each" loop that would retrieve the key names under entries, i.e.:
id
name
age
How can I do this?
Try it
foreach($json->entries as $row) {
foreach($row as $key => $val) {
echo $key . ': ' . $val;
echo '<br>';
}
}
In the $key you shall get the key names and in the val you shal get the values
You could do something like this:
foreach($json->entries as $record){
echo $record->id;
echo $record->name;
echo $record->age;
}
If you pass true as the value for the second parameter in the json_decode function, you'll be able to use the decoded value as an array.
I was not satisfied with other answers so I add my own. I believe the most general approach is:
$array = get_object_vars($json->entries[0]);
foreach($array as $key => $value) {
echo $key . "<br>";
}
where I used entries[0] because you assume that all the elements of the entries array have the same keys.
Have a look at the official documentation for key: http://php.net/manual/en/function.key.php
You could try getting the properties of the object using get_object_vars:
$keys = array();
foreach($json->entries as $entry)
$keys += array_keys(get_object_vars($entry));
print_r($keys);
foreach($json->entries[0] AS $key => $name) {
echo $key;
}
$column_name =[];
foreach($data as $i){
foreach($i as $key => $i){
array_push($column_name, $key);
}
break;
}
Alternative answer using arrays rather than objects - passing true to json_decode will return an array.
$json = '{"entries":[{"id": "29","name":"John", "age":"36"},{"id": "30","name":"Jack", "age":"23"}]}';
$data = json_decode($json, true);
$entries = $data['entries'];
foreach ($entries as $entry) {
$id = $entry['id'];
$name = $entry['name'];
$age = $entry['age'];
printf('%s (ID %d) is %d years old'.PHP_EOL, $name, $id, $age);
}
Tested at https://www.tehplayground.com/17zKeQcNUbFwuRjC

Categories