I am trying to store the user's response for a detailed fitness report questionnaire in MongoDB. Once the form is submitted I would parse the form data and create an array/object which has a predefined structure.
I was thinking of creating a class with the whole object hierarchy with values set to empty string ''. The response I want to store looks like this:
{
"_basic": {
"_response_type": "text",
"_response": {
"name": "eNeMetchH",
"gender": "male",
"age": 20,
"contact": "9876543210",
"email": "email#email.com",
"dob": "1997-03-20",
"package": {
"id": "1001",
"name": "Alpha Monthly",
"start_date": "2017-01-01",
"end_date": "2017-01-31"
}
}
},
"_parq": {
"footnotes": "If yes to one or more questions, please talk to your doctor before you start becoming more physically active or before you have a fitness appraisal. Tell your doctor about the PAR-Q and which questions you have answered yes.",
"response_type": "radio",
"response": [
{
"question": "Has your doctor ever said you have a heart condition and you should only do physical activity that is described by doctor?",
"response": "NO"
},
{
"question": "Do you feel pain in your chest when you do physical activity?",
"response": "NO"
},
{
"question": "In the past month, have you had chest pain when you were not doing physical activity?",
"response": "NO"
},
{
"question": "Do you lose your balance because of dizziness or do you ever lose consciousness?",
"response": "NO"
},
{
"question": "Do you have a bone or joint problem that could not be made worse by a change in your physical activity?",
"response": "NO"
},
{
"question": "Is your doctor currently prescribing drugs for your BP & Heart conditions?",
"response": "NO"
},
{
"question": "Do you know any other reason why you should not do physical activity?",
"response": "NO"
}
]
},
"_conditioning_level": "_intermediate_1_3",
"_occupation": "_professional",
"_primary_goal": "_weight_gain",
"_secondary_goal": "_muscular_strength",
"_workout_intensity": "_mild",
"_availability": {
"_days_per_week": "6",
"_min_per_day": "90"
},
"_sleep": "_insomnia",
"_physical_activity": "_sedentary",
"_stress_level": "_mild",
"_medical_history": [
"_knee_pain",
"_hypertension",
"_high_cholesterol"
],
"_alcohol": "_alcoholic",
"_smoking": "YES",
"_tobacco": "NO",
"_shoe_analysis": {
"_toe_box": "_normal",
"_torsion": "_normal",
"_heel_support": "_abnormal",
"_arch": "_normal"
},
"_postural_analysis": {
"_head_neck": "Blah blah",
"_shoulder": "Blah blah",
"_thoracic_spine": "Blah blah",
"_lumbar_spine": "Blah blah",
"_knee": "Blah blah",
"_feet": "Blah blah"
},
"_anthropometry": {
"_bp": "160/90 mm/Hg",
"_resting_heart_rate": "90 bpm",
"_weight": "82",
"_height": "183",
"_bmi": "20"
},
"_functional_movement": {
"_ssn": "Blah blah",
"_height": "183",
"_weight": "82",
"_primary_score": "Dono",
"_primary_position": "Dono",
"_hand_leg_dominance": "Dono",
"_previous_test_score": "Dono",
"tests": {
"_deep_squat": [
{
"_raw_score": "30",
"_final_score": "40"
}
],
"_hurdle_step": {
"L": {
"_raw_score": "30",
"_final_score": "40"
},
"R": {
"_raw_score": "30",
"_final_score": "40"
}
},
"_inline_lunge": {
"L": {
"_raw_score": "30",
"_final_score": "40"
},
"R": {
"_raw_score": "30",
"_final_score": "40"
}
},
"_shoulder_mobility": {
"L": {
"_raw_score": "30",
"_final_score": "40"
},
"R": {
"_raw_score": "30",
"_final_score": "40"
}
},
"_impingement_clearing_test": {
"L": {
"_raw_score": "30",
"_final_score": "40"
},
"R": {
"_raw_score": "30",
"_final_score": "40"
}
},
"_active_straight_leg_raise": {
"L": {
"_raw_score": "30",
"_final_score": "40"
},
"R": {
"_raw_score": "30",
"_final_score": "40"
}
},
"_trunk_push_up": [
{
"_raw_score": "30",
"_final_score": "40"
}
],
"_press_up_test": [
{
"_raw_score": "30",
"_final_score": "40"
}
],
"_rotary_stability": {
"L": {
"_raw_score": "30",
"_final_score": "40"
},
"R": {
"_raw_score": "30",
"_final_score": "40"
}
},
"_posterior_rocking_test": [
{
"_raw_score": "30",
"_final_score": "40"
}
],
"_total": [
{
"_raw_score": "30",
"_final_score": "40"
}
]
}
},
"_fitness_test": {
"_aerobic_endurance": {
"_distance_covered": "2 km",
"_pre_heart_rate": "72",
"_post_heart_rate": "95",
"_vo2_max": "90",
"_mets": "30"
},
"_muscular_strength": {
"_upper_body": "6",
"_lower_body": "7"
},
"_muscular_endurance": {
"_ab_crunches": "6",
"_free_squats": "7"
},
"_flexibility": {
"_sit_reach": "5",
"_cobra_stretch": "6"
},
"_proprioception": {
"_lt_side": "10",
"_rt_side": "10"
},
"_core_strength": {
"_iron_man": "55"
}
},
"_assessment_summary": {
"_age": "20",
"_sex": "_male",
"_conditioning_level": "_intermediate_1_3",
"_goal": "_weight_gain",
"_occupation": "_professional",
"_stress_level": "_mild",
"_health_problem": "None",
"_test_result": "Need fat loss and Increment in lung capacity",
"_preferences": "None whatsoever"
},
"_remarks": "Blah blah blah"
}
I need to create a template with the above structure intact and empty values. Adding anymore keys or removing keys should not be allowed.
What is the best approach for this?
If you keep the variable as protected, then it can be modified only by member functions and cannot be accessed directly. The __set function will prevent addition of new variable.
create a class
class Foo{
// if you keep the variable as protected, then it can be modified only
// by member functions so noone will be able to remove the variable.
protected $v1;
// this set function will prevent addition of new variable.
public function __set($name, $value) {
throw new Exception("Cannot add new property \$$name to instance of " . __CLASS__);
}
}
Example for a property such as occupation, you have to define it as
protected $occupation = "professional";
Related
I wonder how can I unset the target array whenever i wanted in PHP. It's a product list and the procedure im planning if i want to delete a products. Here's the JSON structure
{
"Merchant": "SAMHONEY",
"date": 1632482493,
"archive": "true",
"extra": "Byahe",
"data": [
{
"product-image": "https:\/\/mobi.asia\/assets\/abunjing-stand.png",
"name": "Sample Product",
"des": "Byahe Palawan Merchant Dashboard v.1.1",
"price": "26"
},
{
"product-image": "https:\/\/mob.asia\/assets\/abunjing-stand.png",
"name": "Sample Product 2",
"des": "Byahe Palawan Merchant Dashboard v.1.1",
"price": "99"
},
{
"product-image": "https:\/\/mob.asia\/01162020\/images\/storage\/1632200295.png",
"name": "Product C",
"des": "Great coffee",
"price": "3"
},
{
"product-image": "https:\/\/mob.asia\/01162020\/images\/storage\/1632200342.png",
"name": "Product A",
"des": "Caramel Coffee",
"price": "4"
}
]
}
What I done in PHP is this
$pos = $_POST['position'];
$jsn = file_get_contents('../datamer/archives/'.$sbd.".json");
$arr = json_decode($jsn, true);
$acc = $arr["data"];
unset($acc[$pos]);
$arr["data"] =$acc;
file_put_contents('../datamer/archives/'.$sbd.".json",json_encode($arr,JSON_PRETTY_PRINT));
And the output is it was re-structuring the JSON into this.Which not im expecting
{
"Merchant": "SAMHONEY",
"date": 1632482493,
"archive": "true",
"extra": "Byahe",
"data": {
"0": {
"product-image": "https:\/\/mobile.byahe.asia\/assets\/abunjing-stand.png",
"name": "Sample Product",
"des": "Byahe Palawan Merchant Dashboard v.1.1",
"price": "26"
},
"2": {
"product-image": "https:\/\/mobile.byahe.asia\/01162020\/images\/storage\/1632200295.png",
"name": "Product C",
"des": "Great coffee",
"price": "3"
},
"3": {
"product-image": "https:\/\/mobile.byahe.asia\/01162020\/images\/storage\/1632200342.png",
"name": "Product A",
"des": "Caramel Coffee",
"price": "4"
}
}
}
Kindly enlighten me to this. I'm still learning,. Thanks in advance for the attention. Well appreciated.
I'm having an issue where my android application is getting a positive result from our key:answer POST, but not from key:array for the same structure. My web developer is saying that I'm not serialising it properly, but every JSON tester I can find on the web is quite happy with the send, just not our web server. I'm sending my JSON in groups of 10 as a string (We had a previous issue where when sending about 200 keys it was giving issues, so I've split it down to 10 per send) and the JSON sent is as follows:
[{
"jobDetails": {
"jobid": "7",
"company": {
"cmid": "30"
}
},
"formName": "IPE Report",
"formHeader": "Activity",
"key": "date_inspDate",
"answervalues": "18-07-2017"
}, {
"jobDetails": {
"jobid": "7",
"company": {
"cmid": "30"
}
},
"formName": "IPE Report",
"formHeader": "Activity",
"key": "text_clientRep",
"answervalues": "testrep"
}, {
"jobDetails": {
"jobid": "7",
"company": {
"cmid": "30"
}
},
"formName": "IPE Report",
"formHeader": "Activity",
"key": "text_designCode",
"answervalues": "destdesign"
}, {
"jobDetails": {
"jobid": "7",
"company": {
"cmid": "30"
}
},
"formName": "IPE Report",
"formHeader": "Activity",
"key": "text_qcPlan",
"answervalues": "testqc"
}, {
"jobDetails": {
"jobid": "7",
"company": {
"cmid": "30"
}
},
"formName": "IPE Report",
"formHeader": "Activity",
"key": "text_equipDesc",
"answervalues": "testdesc"
}, {
"jobDetails": {
"jobid": "7",
"company": {
"cmid": "30"
}
},
"formName": "IPE Report",
"formHeader": "Activity",
"key": "text_companyName",
"answervalues": "testco"
}, {
"jobDetails": {
"jobid": "7",
"company": {
"cmid": "30"
}
},
"formName": "IPE Report",
"formHeader": "Activity",
"key": "text_drawingNo",
"answervalues": "testrev"
}, {
"jobDetails": {
"jobid": "7",
"company": {
"cmid": "30"
}
},
"formName": "IPE Report",
"formHeader": "Activity",
"key": "Detail",
"answervalues": [{
"register": 1,
"values": "act2"
}, {
"register": 2,
"values": "act3"
}]
}, {
"jobDetails": {
"jobid": "7",
"company": {
"cmid": "30"
}
},
"formName": "IPE Report",
"formHeader": "Activity",
"key": "Regulated",
"answervalues": [{
"register": 1,
"values": "YES"
}, {
"register": 2,
"values": "NO"
}]
}, {
"jobDetails": {
"jobid": "7",
"company": {
"cmid": "30"
}
},
"formName": "IPE Report",
"formHeader": "Activity",
"key": "Comments",
"answervalues": [{
"register": 1,
"values": "DIMENSIONS CHECK"
}, {
"register": 2,
"values": "HOLD POINT"
}]
}]
All is fine until it hits the Detail key, which is an array. This structure was sending fine last week, they claim they've changed nothing. Is it really a serialisation issue on my side or is the server just not accepting that key as either value or array?
From your error message:
"JSON parse error: Can not deserialize instance of java.lang.String out of START_ARRAY token;"
I think you problem is in 'answervalues'.
/* in some entries you have it as an array of objects*/
"answervalues": [{
"register": 1,
"values": "YES"
}, {
"register": 2,
"values": "NO"
}]
/* while in other entries as a string */
"answervalues": "testrev"
Talk with your developer to see how this need to be formatted. I believe the string values also need to be passed as an object in a single array. Something like..
"answervalues": [{
"register": 1,
"values":"testrev"
}]
Below is my JSON file:
{
"example": "1",
"example2": 2,
"text": "3",
"info": {
"agent": 4,
"sum": 5,
"collection": [{
"Name": "6",
"Pic": "7"
} {
"Name": "8",
"Pic": "9"
}, {
"Name": "10",
"Pic": "11"
}]
}
}
How would I display each 'name' and 'pic' I think I need to use a foreach loop but don't know how to.
This is all the code I have:
$data = json_decode(file_get_contents('http://linktojson.com'));
echo $data['info']['collection'][0]['Name'];
echo $data['info']['collection'][0]['Pic'];
This should work
$data = json_decode(file_get_contents('http://linktojson.com'));
echo "<pre>".print_r($data,1)."</pre>";
foreach($data->info->collection as $key){
echo $key->Pic;
echo $key->Name;
}
Valid JSON
{
"example": "1",
"example2": 2,
"text": "3",
"info": {
"agent": 4,
"sum": 5,
"collection": [{
"Name": "6",
"Pic": "7"
}, {
"Name": "8",
"Pic": "9"
}, {
"Name": "10",
"Pic": "11"
}]
}
}
I am building an admin backend for an android app. My code provides a json output which the android developer then uses in his app. The developer asked me if it is possible to reduce the hierarchy level in the json output
as in remove the highlighted []0 and put the contents directly inside the []data instead.
This is my current php code
if($type == 1 ) //Handle item display
{
try
{
$query = "SELECT category FROM category";
$result= $DBH->query($query);
while($row = $result->fetch(PDO::FETCH_ASSOC))
{
$cat = $row['category'];
$query1 = "SELECT * FROM item WHERE catagory='$cat'";
$value = $DBH->query($query1);
if($row1 = $value->fetchAll(PDO::FETCH_OBJ)){
$main[] = array('data'=>array($row1));
}
else
{
$main[] = array('data'=>array('catagory'=>$row['category']));
}
}
echo json_encode($main);
$result->closeCursor(); //Close database connection free resources
$DBH = null;
}
catch(PDOException $e){
print $e->getMessage ();
die();
}
}
And the json output being generated
[
{
"data": [
[
{
"id": "2",
"name": "rice",
"price": "20",
"description": "Plain Rice",
"image": "4106_rice.jpg",
"time": "12 mins",
"catagory": "Lunch",
"subcat": ""
},
{
"id": "3",
"name": "item 1",
"price": "32",
"description": "item 1 description",
"image": "1370_2Ckjikljklkljh.jpg",
"time": "10",
"catagory": "Lunch",
"subcat": "Chicken Soup"
},
{
"id": "4",
"name": "hello",
"price": "10",
"description": "fgsdjfsfsdj",
"image": "",
"time": "76",
"catagory": "Lunch",
"subcat": ""
}
]
]
},
{
"data": {
"catagory": "Dinner"
}
},
{
"data": {
"catagory": "Soup"
}
},
{
"data": {
"catagory": "Test"
}
}
]
I am not very sure if I can make the changes he asked or if it is possible. Is it doable?
Your json structure is inconsistent and try this approach, will be easier for the developer to parse
{
"response": [
{
"data": [
{
"id": "2",
"name": "rice",
"price": "20",
"description": "Plain Rice",
"image": "4106_rice.jpg",
"time": "12 mins",
"catagory": "Lunch",
"subcat": ""
},
{
"id": "3",
"name": "item 1",
"price": "32",
"description": "item 1 description",
"image": "1370_2Ckjikljklkljh.jpg",
"time": "10",
"catagory": "Lunch",
"subcat": "Chicken Soup"
},
{
"id": "4",
"name": "hello",
"price": "10",
"description": "fgsdjfsfsdj",
"image": "",
"time": "76",
"catagory": "Lunch",
"subcat": ""
}
]
},
{
"data": [
{
"catagory": "Dinner"
}
]
},
{
"data": [
{
"catagory": "Soup"
}
]
},
{
"data": [
{
"catagory": "Test"
}
]
}
]
}
I am trying to set up a form to allow users to update data in a large JSON file. I have a form that allows the user to grab the 'event' they want and to edit it. When they click submit, it sends the data to a script that pulls the entire JSON file into an array. From there, I need the script to search through that array and find the index of the sub-array that has the same ID as the 'event' that has been edited. So if the user has edited the entry called "William Bradford born", I need the script to match the ID "american-ccincore-1411541230" and return 0 for that sub-array's index.
[
{
"id" : "american",
"title" : "A Timeline of American Literature",
"description" : "LENGTHY DESCRIPTIVE TEXT",
"initial_zoom" : "50",
"focus_date" : "1650-01-01 00:00:00",
"size_importance" : "true",
"timezone" : "-06:00",
"min_zoom" : "20",
"max_zoom" : "80",
"image_lane_height" : "50",
"display_zoom_level" : "1",
"tags" : {
"Puritan" : "0",
"Enlightenment" : "0",
"Romantic" : "0",
"Transcendental" : "0",
"Dark Romantic": "0",
"African American": "0",
"American Indian": "0",
"International" : "0"
},
"legend": [
{
"title": "Author event",
"icon": "star_red.png"
},
{
"title": "Publication event",
"icon": "square_blue.png"
},
{
"title": "Historical event",
"icon": "triangle_green.png"
}
],
"events": [
{
"id": "american-ccincore-1411541230",
"title": "William Bradford born",
"description": "LENGTHY DESCRIPTIVE TEXT",
"tags": "Puritan",
"startdate": "1950-03- 00:00:00",
"enddate": "1657-05- 00:00:00",
"importance": "50",
"date_display": "year",
"link": "",
"image": "https://www.csustan.edu/sites/default/files/ENGLISH/reuben/pal/chap1/bradford.gif",
"icon": "star_red.png",
"span_color": "#f66"
}, {
"id": "american-mforkner-1411364607",
"title": "Church Mission Society",
"description": "LENGTHY DESCRIPTIVE TEXT",
"tags": "",
"startdate": "1799-01-01 00:00:00",
"enddate": "1799-01-01 00:00:00",
"importance": "50",
"date_display": "year",
"link": "",
"image": "http://webarchive.cms-uk.org/_images/tnsaies1.jpg",
"icon": ".png",
"span_color": "#ccc"
}
]
}
]
I've tried to adapt scripts suggested in a dozen or so posts here, but I can't get any to work in this particular situation. Thanks for any advice.
It's just a simple loop. The caveat is you need to distinguish between an answer of 0 and a failure to find the event you were looking for. I typically use false to indicate failure, but that means using === or !== for your comparison later.
function findEventIndexById($events, $target) {
$retval = false;
foreach($events as $index=>$oneEvent) {
if ($oneEvent->id == $target) {
$retval = $index;
break;
}
}
return $retval;
}
$foundIndex = findEventIndexById($data->events, $eventId);
if ($foundIndex !== false) {
// ... do stuff here to $data->events[$foundIndex]
} else
// ... report an error ...