I have a json file in format
{
"list" : {
"1" : {
"thing1" : "description",
"thing2" : "description",
"thing3" : "description"
},
"2" : {
"thing1" : "description",
"thing2" : "description",
"thing3" : "description"
},
etc.
}
I need to search through and return data based on the description of thing 2 but I also need to then return the number of the list. Problem is the json file comes in with the numbers all out of order so I can't just increment a variable as I go through them all.
currently I have my code setup like this:
$json = json_decode($response);
foreach($json->list as $item) {
$i++;
if($item->thing2 == "description") {
echo "<p>$item->thing1</p>";
echo "<p>$item->thing2</p>";
echo "<p>$item->thing3</p>";
echo "<p>position: $i</p><br /><br />";
}
}
unfortunately because the positions are out of order everytime the $i variable is retuning the wrong position. How can I return the title of the item that has the proper thing2 description.
Change
foreach($json->list as $item) {
$i++;
to
foreach($json->list as $i => $item) {
(This is described in the PHP documentation for object iteration.)
The setting the second parameter of json_decode() to TRUE returns an associative array which is a bit more conducive to what you want to do:
$json = json_decode($response, TRUE);
foreach($json['list'] as $key => $item) {
if($item['thing2'] == "description") {
echo "<p>$item['thing1']</p>";
echo "<p>$item['thing2']</p>";
echo "<p>$item['thing3']</p>";
echo "<p>position: $key</p><br /><br />";
}
}
Should do the trick.
json_decode has the option of returning an associative array ($assoc = true). After this, it is trivial to just access $associative_array["2"].
Related
I have a JSON item list in the database that holds the the serial number of different items to be printed according to the order of their serial number. The JSON structure is like this:
{
"item_list": [
{
"item_sl": "1",
"item_print": "flowers"
},
{
"item_sl": "2",
"item_print": "cars"
}
]
}
After retrieving it from the database, I decoded the items in $items_array and then tried to create variables like $item1, $item2 ... which I wanted to assign to the item_print values from the JSON. The same print values have been already defined earlier ($cars, $flowers). Lastly, I wanted to print all of them. The code is:
$cars = 'Tesla is my favorite.';
$flowers = 'I love all flowers.';
$items_array = json_decode($items_data, true);
foreach ($items_array['item_list'] as $item_list) {
foreach ($item_list['item_sl'] as $key => $n) {
${'item'.$n} = $item_list['item_print'][$key];
}
}
$all_print = $item1.' '.$item2;
echo $all_print;
But $all_print is returning null, which tells me my approach is not correct. What am I missing here? What would be a better approach for printing the $cars and $flowers variables according to the serial numbers from the JSON?
First of all, there is no need to use multiple loops when you can achieve the same with a single loop.
Also, there is no need to create variables dynamically and assign values when you can directly decode the JSON and access each value without creating variables and assigning them dynamically.
This should work:
<?php
$items_data = '{
"item_list": [
{
"item_sl": "1",
"item_print": "flowers"
},
{
"item_sl": "2",
"item_print": "cars"
}
]
}';
$items_array = json_decode($items_data, true);
foreach ($items_array['item_list'] as $item) {
${'item' . $item['item_sl']} = $item['item_print'];
}
$all_print = $item1.' '.$item2;
echo $all_print;
?>
Output:
flowers cars
For Your Code above, i don't Really Understand it well, but i think this may help if you are trying to loop items from a json encoded data.
$items_array = json_decode($items_data, true);
foreach ($items_array->item_list as $item_list) {
echo $item_list->item_sl;
echo $item_list->item_print;
}
EDITED
Two Methods to achieve this
First:
$items_array = json_decode($items_data, true);
foreach ($items_array["item_list"] as $item_list) {
echo $item_list["item_sl"];
echo $item_list["item_print"].'<br>';
}
Second:
$items_array = json_decode($items_data);
foreach ($items_array->item_list as $item_list) {
echo $item_list->item_sl;
echo $item_list->item_print;
}
ADDITIONALLY:
if you want to display output based on the user item_print, then you can do this;
$items_array = json_decode($items_data, true);
foreach ($items_array["item_list"] as $item_list) {
if ($item_list["item_print"] == 'cars') {
echo $cars."<br>";
}elseif($item_list["item_print"] == "flowers"){
echo $flowers;
}
}
I am having trouble getting the name of a dynamic key from a JSON string.
I am using PHP
This is a sample of the JSON
{
"_text": "this is a test",
"entities": {
"dynamic_key": [
{
"confidence": 0.99,
"value": "thi is the answer"
}
]
},
"msg_id": "1234532123"
}
I am using foreach to go trough the json key and get the values
foreach ($json as $obj) {
$search_term = $obj->_text;
$msg_id = $obj->msg_id;
}
But I am not sure how to get the value of the "dynamic_key" which changes every time, and because of that I also cannot get the values of "confidence and value" keys.
Any ideas on how to approach this?
Followed #Dimi, solution. This is what I ended up with
$data=json_decode($json,true);
foreach ($data['entities'] as $key=>$val)
{
echo "Entity: $key";
foreach ($data['entities'] as $keys){
$conf = $keys[0]['confidence'];
$answer = $keys[0]['value'];
echo "conf: $conf, answ: $answer";
}
}
Can you provide a couple more examples?
Or try this code and let us know if it breaks
<?php
$json='{
"_text": "this is a test",
"entities": {
"dynamic_key": [
{
"confidence": 0.99,
"value": "thi is the answer"
}
]
},
"msg_id": "1234532123"
}';
$data=json_decode($json,true);
foreach ($data['entities'] as $key=>$val)
{
echo "VALUE IS $key\n values are ";
var_dump($val);
}
Using the data you've shown, there doesn't seem to be an array for the starting JSON.
But with that data the following will use foreach to both fetch the key and the data and then another sub-loop to fetch the confidencevalue...
$search_term = $json->_text;
$msg_id = $json->msg_id;
foreach ( $json->entities as $key => $entities ) {
echo $key.PHP_EOL;
foreach ( $entities as $entity) {
echo $entity->confidence.PHP_EOL;
}
}
If you decode the JSON as an array and if the dynamic key is the only key under entities, then:
$array = json_decode($json, true);
$dynamic = current($array['entities']);
$confidence = $dynamic['confidence'];
$value = $dynamic['value'];
Or shorter:
$confidence = current($array['entities'])['confidence'];
You can probably use reset, current and maybe array_pop etc.
I have some JSON I need to parse in a file test.json.
{
"players":
[
{ "SteamId":123, "Username":"Bob", "Kills":5, "Deaths":7, "Rank":1 },
{ "SteamId":456, "Username":"Nick", "Kills":3, "Deaths":2, "Rank":2 },
{ "SteamId":789, "Username":"Moses" "Kills":8, "Deaths":1, "Rank":3 }
]
}
How can I loop through and display my data. My code so far when I var_dump gives me a NULL
$raw_data = file_get_contents('test.json');
$data = json_decode($raw_data, true);
var_dump($data);
Your code is fine once you place the comma Saty mentioned.
To loop and print some values it would look something like:
foreach($data["players"] as $player){
print "Steam ID: ".$player['SteamId'];
print "Username: ".$player['Username'];
print "Kills: ".$player['Kills'];
print "Deaths: ".$player['Deaths'];
print "Rank: ".$player['Rank'];
}
This could be improved to automatically use the Key value as output with the following:
foreach($data["players"] as $player){
foreach($player as $key => $value){
print $key.": ".$value;
}
}
Depends what you are trying to accomplish and how the data will be viewed, but I expect you would be using HTML template.
Thanks for your time in reading this post.
My php file is receiving a json object. But I am facing issues while decoding it.
My php code:
$data=$_POST['arg1'];
echo $data;
$json = json_decode($data,true);
echo $json;
$i = 1;
foreach($json as $key => $value) {
print "<h3>Name".$i." : " . $value . "</h3>";
$i++;
}
When I echo data results as below.
{
"SCI-2": {
"quantity": 2,
"id": "SCI-2",
"price": 280,
"cid": "ARTCOTSB"
}
}
When I echo $json, result is as it follows :
Array
Name1 : Array.
Please assist as i need tho access the cid and quantity values in the $data.
json_decode returns an array. And to print array you can use print_r or var_dump.
Now to access your values you can try :
$json["SCI-2"]["quantity"] for quantity and $json["SCI-2"]["cid"] for cid.
Demo : https://eval.in/522350
To access in foreach you need this :
foreach($json as $k) {
foreach($k as $key => $value) {
print "<h3>Name".$i." : " . $value . "</h3>";
}
}
Since you do not know the number of items in your object, use this:
$obj = json_decode($json);
After this, iterate the $obj variable and after that, inside the loop, use the foreach to get each property.
foreach($iteratedObject as $key => $value) {
//your stuff
}
I want to echo all expanded_url and urls. echo $name prints results . echo $value doesn't print anything because of nested array. How do I echo all values?
$json ='{ "results" : [ { "entities" :
[ { "urls" : [ { "expanded_url" : "http://www.google.com",
"url" : "http://t.co/WZnUf68j"
}, { "expanded_url" : "http://www.facebook.com",
"url" : "http://t.co/WZnUf68j"
}, { "expanded_url" : "http://www.twitter.com",
"url" : "http://t.co/WZnUf68j"
} ] } ],
"from_user" : "A-user-name",
"from_user_id" : 457304735,
"text" : "Ich R U #BoysNoize #SuperRola"
} ] }';
# $json_array = (array)(json_decode($json));
$data = json_decode($json,true);
foreach($data as $name => $value){
echo $name.'<br>';
echo $value; // NOT WORKING - HOW TO ECHO ALL VALUES
}
You can do that with
$data = json_decode($json,true);
foreach($data["results"][0]["entities"][0]["urls"] as $value){
echo $value['expanded_url']."\n";
echo $value['url']."\n";
}
Since it's a multidimensional array, you can loop through the various levels to reach where you want.
foreach($data['results'] as $item) {
foreach($item['entities'] as $urls) {
foreach($urls['urls'] as $element) {
echo "expanded_url: {$element['expanded_url']} \n";
echo "url: {$element['url']} \n";
}
}
}
Note: The reason I've done the various foreach loops is due to the fact that there may be different results or different entities, so it's better to loop, than to do foreach($data["results"][0]["entities"][0]["urls"] as $value)
Example