PHP JSON getting specific value of each key - php

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) )

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

PHP: Targeting specific JSON array and appending POST data correctly?

I have a JSON file that, in essence, is structured like this:
[{
"name": "James",
"reviews": [
{
"stars": 5,
"body": "great!"
},
{
"stars": 1,
"body": "bad!"
}
]
},
{
"name": "David",
"reviews": [
{
"stars": 4,
"body": "pretty good!"
},
{
"stars": 2,
"body": "just ok..."
}
]
}]
Now when positing new review data for David to a PHP script, how do I target David's specific "reviews" and append it?
I have already decoded everything correctly and have access to both the decoded file and post information. I just don't know how to target David's specific reviews in the JSON array... Thank you in advance!
UPDATE - Just to be clear, everything is decoded already, the POST data and the JSON file from the server. I just need to know how to target David's reviews specifically and append it.
UPDATE 2 - Everyone, please also understand that this is in the case that the index is not known. Doing [1] would be awesome, but when someone submits, they won't know what index it is. The loop for the rendering is being done in AngularJS btw, so can't assign anything on the PHP side for the front-end.
You will have to make use of a for-loop/foreach to iterate through the array testing where arr['name'] === 'David',
then you can access arr['reviews'].
foreach ($array as $person)
{
if ($person['name'] === 'David')
{
$person['reviews'][] = array("stars"=> 3,"body"=> "pretty cool!");
break;
}
}
Edit:
You could also make a generic function for this
function findElem(arr,field,e)
{
foreach ($arr as $elem)
{
if ($elem[field] === e)
{
return $elem;
}
}
return null;
}
to call:
$elem = findElem(myArray,'name','David');
if ($elem !== null)
$elem[] = array("stars"=> 3,"body"=> "pretty cool!");
Looks like more work, but if you are going to do it repeatedly then this helps.
PHP >= 5.5.0 needed for array_column or see below for an alternate:
$array[array_search('David', array_column($array, 'name'))]['reviews'][] = array(
'stars'=>1,'body'=>'meh'
);
Instead of array_column you can use:
array_map(function($v) { return $v['name']; }, $array);
If you want specifically david's reviews, and only david's reviews... assuming that $array holds the json_decoded array:
$david_reviews = $array[1]["reviews"];
foreach($david_reviews as $review){
//Do code to retrieve indexes of array
$stars = $review["stars"] //5
$body = $review["body"] //Great!
}
If you're looking to grab reviews for each result, then user2225171's answer is what you're looking for.
json_decode($json, true) will return you the simple array of data. Then save what you need and save back with json_encode()

Decoding Nested JSON in PHP

Excuse me if this has been covered, but I've looked and can't find an answer that works.
I have the following JSON (shortened for clarity):
[{
"header": {
"msg_type": "0001"
},
"body": {
"event_type": "ARRIVAL",
"train_id": "384T22MJ20"
}
},{
"header": {
"msg_type": "0003"
},
"body": {
"event_type": "DEPARTURE",
"train_id": "382W22MJ19"
}
}]
Now I know I can use json_decode to create a php array, but not knowing much about php I don't know how to get it to do what I want. I need to be able to access a value from each array. For example I would need to extract the train_id from each array. At the moment I have this:
$file = "sampleData.json";
$source = file_get_contents($file);
$data = json_decode($source);
$msgbdy = $data->body;
foreach($msgbdy as $body){
$trainID = $body->train_id;
}
I know this is wrong, but I'm not sure if I'm on the right track or not.
Thanks in advance.
anonymous objects are deserialized as array-members, foreach can handle that :
$objs = json_decode($source)
foreach($objs as $obj)
{
$body = $obj->body; //this is another object!
$header = $obj->header; //yet another object!
}
and within that loop, you can now access msg_type, train_id and event_type via $body and $header
I suggest to pass it true as a parameter, it is easier to work with associative arrays than objects:
$messages = json_decode($source, true);
foreach($messages as $message){
$trainID = $message["body"]["train_id"];
}
You process it in the wrong order: your string is an array of objects. Not an object with arrays.
You first need the large foreach loop to iterate over the array and then access for each element the "body" and "train_id".
Your code should thus read:
foreach($data as $item) {
echo $item->body->train_id; //or do something else with $item->body->train_id
}
Maybe something like:
$data = json_decode($source);
foreach ($data as $message) {
$trainId = $message->body->train_id;
// Not sure what you want to do wit this ^
}
You need to loop over each whole entry. See how where the data is repeated, and that is what you need to loop over.
Your trying to access an array like an object. The array notation would be $data[0]['body'] to retrieve the value for the "body" key in the first entry in the array.

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);

How to get individual fields from JSON in PHP

My JSON looks like this. How do I get a specific field, e.g. "title" or "url"?
{
"status":1,
"list":
{
"204216523":
{"item_id":"204216523",
"title":"title1",
"url":"url1",
},
"203886655":
{"item_id":"203886655",
"title":"titl2",
"url":"url2",
}
},"since":1344188496,
"complete":1
}
I know $result = json_decode($input, true); should be used to get parsable data in $result, but how do I get individual fields out of $result? I need to run through all the members (2 in this case) and get a field out of it.
json_decode() converts JSON data into an associative array. So to get title & url out of your data,
foreach ($result['list'] as $key => $value) {
echo $value['title'].','.$value['url'];
}
echo $result['list']['204216523']['item_id']; // prints 204216523
json_decode() translates your JSON data into an array. Treat it as an associative array because that's what it is.

Categories