PHP and JSON/ How to get a specific elements // - php

I need to parse a JSON file. I've only worked with XML before.
How can I get the second "food_id" (1730905)?
Here is my JSON file:
{
"shopId":29,
"last":46977914,
"freshfood":[
{
"freshfood_id":2629,
"food":[
{
"food_id":1740851,
"type":"fruit",
"status":1
},
{
"food_id":1730905,
"type":"vegetable",
"status":1
},
]
}
]
}
I tried this, but it does not work.
$string = file_get_contents("food.json");
$json_a=json_decode($string,true);
echo $GetFreshFoodId = $json_a['freshfood'][1]['freshfood_id'];

PHP arrays are zero-based, so that should be:
$json_a['freshfood'][0]['food'][1]['food_id'];
Also, note that the JSON is not entirely valid - you should remove the last comma. (But you might have left out additional records in your example JSON for clarity.)

Related

echo results from an google safe browsing api array

I know this is a basic question, but I cannot figure out how to actually do this. I have read countless tutorials about it but they seemingly do not work.
var_dump($google_check);
returns the following:
string(488) "{
"matches": [
{
"threatType": "MALWARE",
"platformType": "LINUX",
"threat": {
"url": "http://malware.testing.google.test/testing/malware/"
},
"cacheDuration": "300s",
"threatEntryType": "URL"
},
{
"threatType": "MALWARE",
"platformType": "LINUX",
"threat": {
"url": "http://malware.testing.google.test/testing/malware/"
},
"cacheDuration": "300s",
"threatEntryType": "URL"
}
]
}
"
I want to echo results from the array, so something like
echo $google_check[0][matches][threat];
echo $google_check[1][matches][threat];
Problem is this returns illegal offset on matches and threat, and only echo's a single character {
What am I doing wrong? How do I echo the results from this array without dumping the entire array?
The response you recieved is in json so you'll need to first json_decode the response.
$decoded = json_decode($google_check, true);
Then you can access it like an array
echo $decoded['matches'][0]['threat'];
echo $decoded['matches'][1]['threat'];
if you want the url value you'll need to do it like this.
echo $decoded['matches'][0]['threat']['url'];
echo $decoded['matches'][1]['threat']['url'];
please also note, when looking at array keys that aren't numerical you'll need to wrap in quotes (e.g. $decoded['matches'] instead of $decoded[matches]).
Here's a quick explanation on json
https://www.tutorialspoint.com/json/json_php_example.htm

How to filter through this properly?

I am wondering how to filter through a result like this properly. What I am doing results in problems. Obviously using a foreach on an array with a single item is not ideal but I don't know exactly how to do it any other way.
// connect with the static file
$json = file_get_contents('resources/assets/datafeeds/brewery_single.json');
$obj = json_decode($json, true);
// create brewery info
foreach($obj['pages'] as $brewery) {
foreach($brewery['results'] as $brewery) {
}
}
I've tried doing something like:
foreach($obj['pages']['results'] as $brewery) {
}
But I get an Undefined index: result errror like this.
Example data with only one result block, my data has multiple:
{
"apiName": "brewery_single",
"apiGuid": "d74e8aa2-4064-44b9-81de-2ceb150882c0",
"generatedAt": 1452761620,
"pages": [
{
"pageUrl": "http://www.brewery-website.com",
"results": [
{
"website": "www.brewery.com/",
"plaats": "Place",
"latlong": [
"53.657856",
"5.032597"
],
"naam": "Brouwerij title",
"provincie": "Noord Brabant",
"afbeelding": "http://www.brewery.com/images/brewery/brewer.jpg",
"actief": "Yes",
"land": "Netherlands",
"adres": "<p><b>Adres:</b><br />Street 40 <br />2388 GP<br /> Province, Netherlands </p>",
"opgericht": "1990"
}
]
},
]
}
Hopefully somebody can help me out so I can properly get my data from an api.
It seems like pages is an array of potentially multiple pages, each of which contains a results array of potentially multiple results. So indeed, two loops are in order:
foreach ($obj['pages'] as $page) {
foreach ($page['results'] as $brewery) {
...
}
}
If you're only ever interested in the first result, you can try to directly access it:
if (isset($obj['pages'][0]['results'][0])) {
echo $obj['pages'][0]['results'][0]['plaats'];
}
But again, the point of this data structure appears to be to account for multiple results, so you may be missing out on some information if you only ever consider the first.
Consult the documentation (which hopefully exists) of that API for exact details on the returned data.
Add an extra check to see if the data that you want is in the array:
if (isset($obj['pages'])) {
foreach($obj['pages'] as $brewery) {
if (isset($brewery['results'])) {
foreach($brewery['results'] as $brewery) {
}
}
}
}
There is syntax error in your code near ['results]
Change from
foreach($obj['pages']['results] as $brewery) {
into
foreach($obj['pages']['results'] as $brewery) {
There is no multiple arrays in results array. So why you need foreach there?
Anyways you can get value of results by providing exact INDEX.
For example: echo $obj['pages']['results]['website'];

Trying to count the length of an array from JSON list

I am trying to count the length of an array that I converted from JSON using json_decode in php but it is not working for some reason. This is my current code. The JSON list contains an array that has 10,000 items. I am pretty sure that I am missing something. Any help will be greatly appreciated.
PHP
<?php
$fl = file_get_contents($somepath);
$text = json_decode($fl, true);
$len = count($text["alphalist"]);
echo $len;
?>
JSON
{
"alphalist": [{
"a": "alphabet1."
}, {
"b": "alphabet2."
}, {
"c": "alphabet3."
}, {
"d": "alphabet4."
}, {
"e": "alphabet5."
}
....
{
"zzzzz": "alphabet10000."
}
]
}
The answer was actually here in response to another similar question.
PHP not converting JSON using 'json_decode()'
So after some testing with user D4V1D, it turns out that the problem was due to the PHP function json_decode not working because it wasn't in the UTF-8 format. The workaround for this is
$fl = file_get_contents($somepath);
$text = json_decode(utf8_encode($fl), true);
$len = count($text["alphalist"]);
Now $len will give the correct array length. If there is any error or improvement to be made in my explanation, just place it in the comments and I will correct it accordingly.

parse Javascript json into php

Here is my Json. This ia an dwr response ( a webservice created in java) .
{
key1 : {
date : "Today" ,
items : [
{
itemKey1 : "itemValue1",
itemKey2 : "itemValue2",
},
{
itemKey1 : "itemValue1",
itemKey2 : "itemValue2",
},
]
}
}
JSON LINT is also showing the error.
If you can see key do not have "" may be that's why i can not parse it to json in php directly. Is there any way oi can parse it to json and then to array or directly to an array.
But when i transfor this to this type of json it. In JSON LINT it shows that it is proper json.
{
"key1": {
"date": "Today",
"items": [
{
"itemKey1": "itemValue1",
"itemKey2": "itemValue2"
},
{
"itemKey1": "itemValue1",
"itemKey2": "itemValue2"
}
]
}
}
So is there anyway i can trasnfer json to second type. Dynamically in PHP
Since there is no javascript parser build in to PHP and what you have here is JAVASCRIPT and not JSON, your only options is really to implement your own parser / use an existing parser. OR wrangle your string into being JSON, this COULD be done with something like regex, though it will most likely be flaky.
For your specified example data, this would do:
<?php
$data = json_decode(preg_replace_callback('#(\S+)\s*:#i', function($matches){
return '"'.$matches[1].'" :';
},$str));

How would I parse this json?

I've been having issues trying to parse this json data.
I tried to do this to return the name but its not working:
foreach(json_decode($test) as $item){
$name= $item->users->name;}
This is the json code:
{
"users":[
{
"id":"dsfdfsd",
"id_str":"dsfsdf",
"name":"Davy",
"screen_name":"Davy232",
"location":"Colorado"
},
{
"id":"wer",
"id_str":"wer",
"name":"Sarah",
"screen_name":"Davy232",
"location":"LA"
},
{
"id":"fdf",
"id_str":"fdf",
"name":"James",
"screen_name":"James374",
"location":"Vegas"
}
]
}
That is because the JSON is invalid , Here's the proper fixed JSON
Fixed JSON Data
{
"users":[
{
"id":"dsfdfsd",
"id_str":"dsfsdf",
"name":"Davy",
"screen_name":"Davy232",
"location":"Colorado"
}
]
}
What were the problems ?
You did not surround dsfdfsd with doubles quotes.
There was an extra comma after Colorado
The braces were not properly balanced.
Also, your foreach should be like this..
foreach(json_decode($test) as $item){
echo $item[0]->name;
}
Working Demo - Part 1
Working Demo - Part 2

Categories