Get JSON Group Name By ID, Not Value - php

I have a valid JSON file like this:
{
"default": {
"key_value": "Default Value"
},
"test": {
"key_value": "Test Value"
}
}
I want to get the group names as a string: "default" and "test".
I know that i could use something like:
{
"general": {
"id": "default",
"key_value": "Default Value"
},
{
"id": "test",
"key_value": "Test Value"
}
}
But since my JSON is valid and my functions for reading and saving the file are already working fine, i want to achieve this with the original structure.
For experimenting I got something like:
$json = file_get_contents("file.json");
$json_data = json_decode($json, true); // I guess assoc must be true?
foreach ($json_data as $item) } // My hope was that i am able to read $item, however it is an array
echo $item["key_value"]."<br />"; // That gives me "Default Value" and "Test Value", so thats at least something
}
I guess "default" and "test" are within the first array of the json?
Now i need to find a way to read them and save them as a string.
A foreach couldn't be that wrong since if a group like "test2" is added, i want to read it aswell.
I am struggling with undefined and illegal offsets (since i cant use arrays as keys?).
Since I am getting the values with something like:
$json_data["default"]["key_value"]
I thought there is something like $json_data[0] which should be "default".
Apparently, this is also an array right? I've already looked around in the forums already, but unfortunately no one had the same JSON structure as their problems got solved.
Maybe it's just dumb to use it like this, but there must be a way to make it work right?
Possibly it's just 3 lines of code aswell and i'm not getting there right now... I've tried so much already.
Maybe you guys can help me with that.

I think what you want is this:
foreach($json_data as $key=>$value) {
echo $key, "<br />\n";
}
If you want it a bit nicer you can use array_keys():
foreach(array_keys($json_data) as $key) {
echo $key, "<br />\n";
}

You have to try this loop :
foreach ($array as $key => $value) {
// you could print here the key or value
}

Related

Get JSON Data From .json (php)

i'm trying to get the fields "name, price, image and rarity" to show in a php file, anyone can help me? Thanks ;D
{
"status": 300,
"data": {
"date": "2019-09-16T00:00:00.000Z",
"featured": [
{
"name": "Flying Saucer",
"price": "1,200",
"images": {
"icon": icon.png",
},
"rarity": "epic",
},
I'm using this that a friend told me, but i cant put that to work :c
<?php
$response = json_decode(file_get_contents('lista.json'), true);
foreach ($response as $val) {
$item = $val['name'];
echo "<b>$item</b>";
}
?>
I'm not quite sure what you are trying to achieve. You can just access the contents via the $response array like this:
echo $response['status']; // would output 300
You can use foreach to iterate through the array. For example: If you want to output the name of every element of the array you can use:
foreach ($response['data'] as $val) { // loop through every element of the data-array (if this makes sense depends on the structure of the json file, cant tell because it's not complete)
echo $val['featured']['name'];
}
You gotta get the index in $val['data']['featured']['name'] to retrieve the name index.
When you defined the second parameter of json_decode, you said that you want your json to be parsed to an array. The brackets in the original json identify when a new index of your parsed array will begin.
I suggest you to read about json_decode and json in general:
JSON: https://www.json.org/
json_decode function: https://www.php.net/manual/en/function.json-decode.php

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

json_encode - formatting issue?

I am requesting my output look like this:
Response
{
error_num: 0
error_details:
[
{
"zipcode": 98119
},
{
"zipcode": 98101
}
]
}
The values are irrelevant for this example.
My code looks like this:
$returndata = array('error_num' => $error_code);
$returndata['error_details'] = $error_msg;
$temp_data = array();
$temp_value = '';
foreach ($zipcodes_array as $value) {
//$temp_data['zipcode'] = $value;
//$temp_value .= json_encode($temp_data);
$temp_value .= '{"zipcode":$value},';
}
//$returndata['test'] = $temp_value;
$returndata['zipcodes'] = $temp_value;
echo json_encode($returndata);
My output varies depending on my different attempts (which you can see with the commented out things) but basically, I don't understand how the 3rd part (the part with the zipcodes) doesn't have a key or a definition before the first open bracket "["
Here is the output for the code above:
{"error_num":0,"error_details":"","zipcodes":"{\"zipcode\":11111},{\"zipcode\":11112},{\"zipcode\":11113},{\"zipcode\":22222},{\"zipcode\":33333},{\"zipcode\":77325},{\"zipcode\":77338},{\"zipcode\":77339},{\"zipcode\":77345},{\"zipcode\":77346},{\"zipcode\":77347},{\"zipcode\":77396},{\"zipcode\":81501},{\"zipcode\":81502},{\"zipcode\":81503},{\"zipcode\":81504},{\"zipcode\":81505},{\"zipcode\":81506},{\"zipcode\":81507},{\"zipcode\":81508},{\"zipcode\":81509},"}
Obviously i did not show the variables being filled/created because its through MySQL. The values are irrelevant. Its the format of the output i'm trying to get down. I don't understand how they have the "zipcode": part in between {} brackets inside another section which appears to be using JSON_ENCODE
It is close but see how it still has the "zipcodes": part in there defining what key those values are on? My question is, is the "response" above being requested by a partner actually in JSON_ENCODE format?? or is it in some custom format which I'll just have to make w/out using any json features of PHP? I can easily write that but based on the way it looks in the example above (the response) I was thinking it was JSON_ENCODE being used.
Also, it keeps putting the \'s in front of the " which isn't right either. I know it's probably doing that because i'm json_encode'ing a string. Hopefully you see what i'm trying to do.
If this is just custom stuff made to resemble JSON, I apologize. I've tried to ask the partner but I guess i'm not asking the right questions (or the right person). They can never seem to give me answers.
EDIT: notice my output also doesn't have any [ or ] in it. but some of my test JSON_ENCODE stuff has had those in it. I'm sure its just me failing here i just cant figure it out.
If you want your output to look like the JSON output at the very top of your question, write the code like this:
$returndata = array('error_num' => $error_code);
$returndata['error_details'] = array();
foreach ($zipcodes_array as $value) {
$returndata['error_details'][] = array('zipcode' => (int)$value);
}
echo 'Response ' . json_encode($returndata);
This will return JSON formatted like you requested above.
Response
{
error_num: 0
error_details:
[
{
"zipcode": 98119
},
{
"zipcode": 98101
}
]
}
Can you just use single ZipCode object as associative array, push all your small ZipCode objects to the ZipCodes array and encode whole data structure. Here is the code example:
$returndata = array(
'error_num' => $error_code,
'error_details' => array()
);
foreach ($zipcodes_array as $value) {
$returndata['error_details'][] = array('zipcode' => $value);
}
echo json_encode($returndata);

PHP JSON getting specific value of each key

I have a php code that reads JSON files. Part of the JSON sample below:
"Main": [{
"count": 7,
"coordinates": [89,77],
"description": "Office",
},{
"count": 8,
"coordinates": [123,111],
"description": "Warehouse",
}]
and I am trying to code PHP to only get the info (count, coordinates, description) of those who's description is included in the criteria like Warehouse. PHP Sample below
$validcriteria = array("Warehouse", "Parking_lot");
How do I do an if-statement to check first if "description" is included in the valid criteria. I tried the code below but it doesn't seem to work right.
$JSONFile = json_decode($uploadedJSONFile, false);
foreach ($JSONFile as $key => $value)
{
if (in_array($key['description'] , $validcriteria))
{
#more codes here
}
}
My code in PHP has been working except when I try to add $key['description'] to try and check the description first if it's valid. My code above is reconstructed to remove sensitive information but I hope you got some idea of what I was trying to do.
When attempting to understand the structure of a parsed JSON string, start with a print_r($JSONFile); to examine its contents. In your case, you will find that there is an outer key 'Main' which holds an array of sub-arrays. You will need to iterate over that outer array.
// Set $assoc to TRUE rather than FALSE
// otherwise, you'll get an object back
$JSONFile = json_decode($uploadedJSONFile, TRUE);
foreach ($JSONFile['Main'] as $value)
{
// The sub-array $value is where to look for the 'description' key
if (in_array($value['description'], $validcriteria))
{
// Do what you need to with it...
}
}
Note: if you prefer to continue setting the $assoc parameter to false in json_decode(), examine the structure to understand how the objects lay out, and use the -> operator instead of array keys.
$JSONFile = json_decode($uploadedJSONFile, FALSE);
foreach ($JSONFile->Main as $value)
{
// The sub-array $value is where to look for the 'description' key
if (in_array($value->description, $validcriteria))
{
// Do what you need to with it...
}
}
You might also consider using array_filter() to do the test:
$included_subarrays = array_filter($JSONFile['Main'], function($a) use ($validcriteria) {
return in_array($a['description'], $validcriteria);
});
// $included_subarrays is now an array of only those from the JSON structure
// which were in $validcriteria
Given your JSON structure, you probably want
foreach($decoded_json['Main'] as $sub_array) {
if (in_array($sub_array['description'], $validation)) {
... it's there ...
}
}
Because you set false to second argument of json_decode function, it's returned as an object,
if you change it to TRUE, the code would work.
http://php.net/manual/en/function.json-decode.php
and you have to change key to value;
foreach ($JSONFile->Main as $key => $value)
{
if (in_array($value->description, $validcriteria))
{
#more codes here
}
}
this code assume your json file has one more depth greater than your example. that's why $JSONFile->Main in the foreach loop.
Try to use that :
if ( array_key_exists('description', $key) )

Categories