PHP - Foreach variable works only if read - php

I am trying to read posts under each category as shown below. There are multiple categories with id "4", "3", "2", "1". Only for category "1" there is a post available.
foreach ($wp_categories as $wp_category) {
$id = $wp_category->term_taxonomy_id;
//if($id == "1") {
$posts = $json_api->introspector->get_posts(array(
'cat' => $id
));
//}
$result[] = $posts;
}
return $result;
In the above code if I just uncomment the if condition, I am getting the posts in the result array. But if this is commented I am not getting the posts in result.
I am new to PHP and above condition is not making any sense. It would be of great help if someone could explain why having the if condition is making the post available in the result.
dumping $wp_categories below
{
"status": "ok",
"0": {
"term_id": "5",
"name": "Category 5",
"slug": "category5",
"term_group": "0",
"term_order": "1",
"term_taxonomy_id": "5",
"taxonomy": "category",
"description": "",
"parent": "0",
"count": "0"
},
"1": {
"term_id": "2",
"name": "Category 4",
"slug": "category4",
"term_group": "0",
"term_order": "2",
"term_taxonomy_id": "2",
"taxonomy": "category",
"description": "",
"parent": "0",
"count": "0"
},
"2": {
"term_id": "3",
"name": "Category 3",
"slug": "category3",
"term_group": "0",
"term_order": "3",
"term_taxonomy_id": "3",
"taxonomy": "category",
"description": "",
"parent": "0",
"count": "0"
},
"3": {
"term_id": "4",
"name": "abc",
"slug": "abc",
"term_group": "0",
"term_order": "4",
"term_taxonomy_id": "4",
"taxonomy": "category",
"description": "",
"parent": "0",
"count": "0"
},
"4": {
"term_id": "1",
"name": "Others",
"slug": "others",
"term_group": "0",
"term_order": "5",
"term_taxonomy_id": "1",
"taxonomy": "category",
"description": "",
"parent": "0",
"count": "1"
}
}

This is simply shows that it will be true only in case of id 1:
if($id == "1") {
I think this should be:
if(isset($id) && $id != '') {
to get the all the post.

Related

how to do pagination complex array in cakephp rest-api?

CakePHP Rest-API pagination in an array of array. Like, containable model pagination in CakePHP for reducing API load.
Some existing code :
$this->request->data['page'];
$data = $this->Model1->find('all',array(
'contain' => array('Model2'),
'fields' => array(),
'conditions' => array('Model1.status' => 1 )
));
Below API response and I want to paginate in ProductUser array because when lots of product load at one-time app will be hang. It's possible or any other way to reduce data load in CakePHP.
API Response :
"status": true,
"message": "Available devices!",
"data": [
{
"id": "6",
"name": "Television",
"parent_id": "0",
"image": "",
"status": "1",
"created": "2019-06-10 15:22:44",
"modified": "2019-06-10 15:22:44",
"ProductUser": [ //Paginate this array
{
"id": "1",
"user_id": "17",
"category_id": "6",
"brand_id": "1",
"product_id": "17",
"date_of_purchase": "2019-06-22",
"seller_id": "1",
"warranty_year": "0",
"warranty_month": "0",
"warranty_end_date": null,
"purchese_price": null,
"bill_upload": "",
"emi_year": "0",
"emi_month": "0",
"emi_start_date": null,
"emi_end_date": null,
"insurance_company_id": "0",
"insurance_year": "0",
"insurance_month": "0",
"insurance_end_date": null,
"created": "2019-06-22 14:13:01",
"modified": "2019-06-22 14:17:07",
"Product": {
"id": "17",
"category_id": "6",
"brand_id": "1",
"product_code": "Samsung LED TV 39 inch",
"name": "Samsung LED TV 39 inch",
"selling_price": "13000",
"short_description": "Television",
"image": "catalog\/sam39.jpg",
"status": "1",
"created": "2019-05-14 00:00:00",
"modified": "2019-05-14 00:00:00"
}
},
{
"id": "1",
"user_id": "17",
"category_id": "6",
"brand_id": "1",
"product_id": "17",
"date_of_purchase": "2019-06-22",
"seller_id": "1",
"warranty_year": "0",
"warranty_month": "0",
"warranty_end_date": null,
"purchese_price": null,
"bill_upload": "",
"emi_year": "0",
"emi_month": "0",
"emi_start_date": null,
"emi_end_date": null,
"insurance_company_id": "0",
"insurance_year": "0",
"insurance_month": "0",
"insurance_end_date": null,
"created": "2019-06-22 14:13:01",
"modified": "2019-06-22 14:17:07",
"Product": {
"id": "17",
"category_id": "6",
"brand_id": "1",
"product_code": "Samsung LED TV 39 inch",
"name": "Samsung LED TV 39 inch",
"selling_price": "13000",
"short_description": "Television",
"image": "catalog\/sam39.jpg",
"status": "1",
"created": "2019-05-14 00:00:00",
"modified": "2019-05-14 00:00:00"
}
}
]
}]

Parsing (3rd) Nested JSON with PHP

I am trying to parse following JSON with PHP but at the very last level ("bank") having some issues, following is the information:
JSON:
{
"loan": {
"fu": "1046",
"vb": "84",
"loan_type": "1",
"type_cocg": "14",
"meeting_place": "PLACE",
"meeting_date": "2019-05-29",
"creation_date": "2019-05-29 12:49:53",
"user_id": "1001-1556",
"member": [{
"mem_id": "1",
"name": "FIRST MEMBER",
"parentage": "PARENTAGE",
"cnic": "3393399393393",
"gender": "1",
"dob": "1994-05-29",
"marital_status": "1",
"spouse_name": "SPOUSE",
"spouse_cnic": "9939439939393",
"pres_address": "PRES ADDRESS",
"perma_address": "PERMA ADDRESS",
"mother_name": "MOTHER NAME",
"cell": "94494944949",
"loan_amount": "30000",
"network": "1",
"sim_ownership": "2",
"co_status": "3",
"occupation_category": "2",
"agri_occ": "null",
"nonagri_occ": "3",
"education": "1",
"disability": "2",
"religion": "6",
"head": "2",
"purpose": "2",
"repayment_mode": "null",
"duration": "4",
"purpose_ent": "null",
"purpose_agri": "null",
"area_unit": "2",
"agri_investment": "",
"agri_expense": "",
"purpose_livestock": "3",
"loan_id_mem": "1",
"monthly_income": "15000",
"monthly_expense": "2000",
"monthly_saving": "13000",
"yearly_saving": "156000",
"male": "2",
"female": "2",
"children": "2",
"cow": "2",
"buffalo": "2",
"goat": "2",
"sheep": "2",
"agri_area_unit": "1",
"land_own": "3",
"land_lease": "3",
"house_own": "3",
"house_rent": "3",
"caste": "CASTE",
"active_loan": "1",
"bank": [{
"id": "1",
"loan_id": "1",
"loan_mem_id": "1",
"bank_id": "1",
"bank_loan": "",
"bank_remaining": "2000",
"purpose": "1",
"purpose_agri": "16",
"purpose_livestock": "null",
"purpose_ent": "null"
}, {
"id": "2",
"loan_id": "1",
"loan_mem_id": "1",
"bank_id": "6",
"bank_loan": "",
"bank_remaining": "500",
"purpose": "3",
"purpose_agri": "16",
"purpose_livestock": "null",
"purpose_ent": "14"
}]
}, {
"mem_id": "2",
"name": "SECOND MEMBER",
"parentage": "PARENTAGE",
"cnic": "3939939393399",
"gender": "1",
"dob": "1994-05-29",
"marital_status": "1",
"spouse_name": "SPOUSE",
"spouse_cnic": "4949949494999",
"pres_address": "ADDRESS",
"perma_address": "ADDRESS",
"mother_name": "MOTHER",
"cell": "49494949494",
"loan_amount": "20000",
"network": "1",
"sim_ownership": "2",
"co_status": "2",
"occupation_category": "2",
"agri_occ": "null",
"nonagri_occ": "2",
"education": "1",
"disability": "1",
"religion": "1",
"head": "1",
"purpose": "1",
"repayment_mode": "null",
"duration": "3",
"purpose_ent": "null",
"purpose_agri": "16",
"area_unit": "1",
"agri_investment": "1500",
"agri_expense": "2000",
"purpose_livestock": "3",
"loan_id_mem": "1",
"monthly_income": "15000",
"monthly_expense": "200",
"monthly_saving": "14800",
"yearly_saving": "177600",
"male": "0",
"female": "0",
"children": "2",
"cow": "2",
"buffalo": "2",
"goat": "2",
"sheep": "2",
"agri_area_unit": "1",
"land_own": "3",
"land_lease": "3",
"house_own": "3",
"house_rent": "2",
"caste": "CASTE 2",
"active_loan": "1",
"bank": [{
"id": "3",
"loan_id": "1",
"loan_mem_id": "2",
"bank_id": "6",
"bank_loan": "",
"bank_remaining": "300",
"purpose": "1",
"purpose_agri": "43",
"purpose_livestock": "null",
"purpose_ent": "null"
}]
}]
}
}
PHP code:
$json = json_decode($content, true);
$json['loan']['fu']; // This works !
foreach($json['loan']['member'] as $item) {
$name = $item['name']; // This works !
foreach($json['loan']['member']['bank'] as $bank_item) { // THIS DOES NOT WORKS!
}
}
The last foreach loop gives out en error saying:
Notice: Undefined index: bank
Are there any clues as to what might be causing the issue, or is there some improved way of parsing the same JSON, that would be very helpful.
Your json parsing is fine. your accessing is missing index.
As the "bank" is inside an array of "member" you should access as $json['loan']['member'][0]['bank'] (the 0 is hard coded - you can switch for 1 also).
If you use for then you should do:
foreach($json['loan']['member'] as $item) {
$name = $item['name']; // This works !
foreach($item['bank'] as $bank_item) { // use $item
}
}
Use only a single foreach() and get the bank element value. If you further need to loop on bank element then you can use another foreach()
$json = json_decode($content, true);
foreach($json['loan']['member'] as $item) {
print_r($item['bank']);
foreach($item['bank'] as $bank_item) {
echo $bank_item;
}
}
DEMO: https://3v4l.org/qB8mV
You have missed that member is also multidimensional array
$json = json_decode($content, true);
/*
echo "<pre>";
print_r($json);
echo "</pre>";*/
foreach($json['loan']['member'] as $item => $value) {
$name = $value['name']; // This works !
foreach($json['loan']['member'][$item]['bank'] as $bank_item) { // THIS DOES NOT WORKS!
print_r($bank_item);
}
}
You can use array_walk_recursive() function also
$json = json_decode($content, true);
$i=0;
foreach($json['loan']['member'] as $item) {
array_walk_recursive($json['loan']['member'][$i]['bank'], function($value,$key) {
echo $key.' :'.$value ." \n";
});
$i++;
}
DEMO : https://3v4l.org/KDR6V

Sorting only a part of object/array in PHP

I've been struggling around this for a while now and can't seem to get the right algorithm.
What I want is to sort this:
$variable = '{
"0": {
"id": "0",
"code": "main_colour",
"label": "Main Colour",
"options": [{
"id": "825",
"label": "White",
"products": ["1", "2", "3"]
}, {
"id": "840",
"label": "Cream",
"products": ["3", "4", "5"]
}],
"position": "0"
},
"2": {
"id": "0",
"code": "size",
"label": "Size",
"options": [{
"id": "825",
"label": "S",
"products": ["1", "2", "3"]
}, {
"id": "840",
"label": "M",
"products": ["3", "4", "5"]
}],
"position": "0"
}
}';
And the output would be
$variable = '{
"0": {
"id": "0",
"code": "main_colour",
"label": "Main Colour",
"options": [{
"id": "840",
"label": "Cream",
"products": ["3", "4", "5"]
},{
"id": "825",
"label": "White",
"products": ["1", "2", "3"]
}],
"position": "0"
},
"2": {
"id": "0",
"code": "size",
"label": "Size",
"options": [{
"id": "840",
"label": "M",
"products": ["3", "4", "5"]
}, {
"id": "825",
"label": "S",
"products": ["1", "2", "3"]
}],
"position": "0"
}
}';
So basically it should be sorted using the label inside the "options" without affecting the other fields. I've been trying usort and tried different algorithms but to no avail.
Current code that sorts only the outside "label" and not the inner label:
function optionsSort($a, $b) {
return strcmp($a['options'][0]['label'], $b['options'][0]['options']['label']);
}
usort($variable, "optionsSort"));
Here's the code:
// your array
$variable = '{
"0": {
"id": "0",
"code": "main_colour",
"label": "Main Colour",
"options": [{
"id": "825",
"label": "White",
"products": ["1", "2", "3"]
}, {
"id": "840",
"label": "Cream",
"products": ["3", "4", "5"]
}],
"position": "0"
},
"2": {
"id": "0",
"code": "size",
"label": "Size",
"options": [{
"id": "825",
"label": "S",
"products": ["1", "2", "3"]
}, {
"id": "840",
"label": "M",
"products": ["3", "4", "5"]
}],
"position": "0"
}
}';
$a = json_decode($variable);
foreach ($a as $item) {
// sorting function
usort($item->options, function($a, $b) { return strcmp($a->label, $b->label); });
}

How to show one array in another array in php?

I have table of a survey,answer and user. Answer and survey table is linked by user_id also user and survey is linked with user_id.
I want to show answers and user and comment for a survey. comment is inside survey table.
I want to get the result in this format:
{
result:1,
message:'success',
survey:[
{
answers:
[
],
user:
{
}
comment:
},
{
answers:
[
],
user:
{
}
comment:
}
]
}
getAllSurveyByDoctor function:
function getAllSurveyByDoctor($user_id)
{
$database = new SurveyDatabase(SurveyConstants::DBHOST,SurveyConstants::DBUSER,SurveyConstants::DBPASS,SurveyConstants::DBNAME);
$dbConnection = $database->getDB();
$stmt = $dbConnection->prepare("SELECT * from survey where `user_id` = ?");
$stmt->execute(array($user_id));
$survey = $stmt->fetchAll(PDO::FETCH_ASSOC);
$surveys = array();
$answers = array();
if (count($survey) > 0) {
foreach($survey as $row)
{
$stmt = $dbConnection->prepare("SELECT answer.answer_id, answer.survey_id, answer.question_id, answer.rating, answer.user_id, question.question_id, question.question, question.type FROM `answer` INNER JOIN `question` ON
answer.question_id = question.question_id WHERE answer.user_id = ? and answer.survey_id = ?");
$s_id = $row['survey_id'];
$stmt->execute(array($user_id,$s_id));
$answer = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt = $dbConnection->prepare("SELECT users.user_id,users.email_id,users.pass,users.address,users.name,survey.survey_id,survey.user_id FROM `users` INNER JOIN `survey` ON users.user_id = survey.user_id WHERE users.user_id = ?");
$stmt->execute(array($user_id));
$user = $stmt->fetch(PDO::FETCH_ASSOC);
$comment = $row['comment'];
// $surveys[] = $row;
$answers = $answer;
$surveys[] = $answers;
$surveys[] = $user;
$surveys[] = $comment;
}
$response = array("status" => 1, "message" => "Success", "surveys" => $surveys);
return json_encode($response);
}
else {
$response = array("status"=>-1,"message"=>"surveys list is empty");
return json_encode($response);
}
}
I get the result like this:
{
"status": 1,
"message": "Success",
"surveys": [
[
{
"answer_id": "50",
"survey_id": "35",
"question_id": "1",
"rating": "4",
"user_id": "9",
"question": "Scheduling appointments",
"type": "rating"
},
{
"answer_id": "51",
"survey_id": "35",
"question_id": "2",
"rating": "6",
"user_id": "9",
"question": "Office environment",
"type": "rating"
}
],
{
"user_id": "9",
"email_id": "user7#gmail.com",
"pass": "user7",
"address": "miraroad",
"name": "user7",
"survey_id": "35"
},
"0",
[],
{
"user_id": "9",
"email_id": "user7#gmail.com",
"pass": "user7",
"address": "miraroad",
"name": "user7",
"survey_id": "35"
},
"0",
[
{
"answer_id": "54",
"survey_id": "37",
"question_id": "1",
"rating": "4",
"user_id": "9",
"question": "Scheduling appointments",
"type": "rating"
},
{
"answer_id": "55",
"survey_id": "37",
"question_id": "2",
"rating": "6",
"user_id": "9",
"question": "Office environment",
"type": "rating"
}
],
{
"user_id": "9",
"email_id": "user7#gmail.com",
"pass": "user7",
"address": "miraroad",
"name": "user7",
"survey_id": "35"
},
"0",
[],
{
"user_id": "9",
"email_id": "user7#gmail.com",
"pass": "user7",
"address": "miraroad",
"name": "user7",
"survey_id": "35"
},
"csdcs",
[
{
"answer_id": "72",
"survey_id": "49",
"question_id": "7",
"rating": "5",
"user_id": "9",
"question": "Doctor listens and answers questions",
"type": "rating"
},
{
"answer_id": "73",
"survey_id": "49",
"question_id": "6",
"rating": "5",
"user_id": "9",
"question": "Doctor explains medical condition(s)",
"type": "rating"
}
],
{
"user_id": "9",
"email_id": "user7#gmail.com",
"pass": "user7",
"address": "miraroad",
"name": "user7",
"survey_id": "35"
},
"",
[
{
"answer_id": "74",
"survey_id": "50",
"question_id": "8",
"rating": "5",
"user_id": "9",
"question": "Doctor spends enough time with patients",
"type": "rating"
},
{
"answer_id": "75",
"survey_id": "50",
"question_id": "3",
"rating": "5",
"user_id": "9",
"question": "Staff helpfulness",
"type": "rating"
}
],
{
"user_id": "9",
"email_id": "user7#gmail.com",
"pass": "user7",
"address": "miraroad",
"name": "user7",
"survey_id": "35"
},
"",
[
{
"answer_id": "76",
"survey_id": "51",
"question_id": "7",
"rating": "5",
"user_id": "9",
"question": "Doctor listens and answers questions",
"type": "rating"
},
{
"answer_id": "77",
"survey_id": "51",
"question_id": "6",
"rating": "5",
"user_id": "9",
"question": "Doctor explains medical condition(s)",
"type": "rating"
}
],
{
"user_id": "9",
"email_id": "user7#gmail.com",
"pass": "user7",
"address": "miraroad",
"name": "user7",
"survey_id": "35"
},
"",
[
{
"answer_id": "78",
"survey_id": "52",
"question_id": "8",
"rating": "5",
"user_id": "9",
"question": "Doctor spends enough time with patients",
"type": "rating"
},
{
"answer_id": "79",
"survey_id": "52",
"question_id": "5",
"rating": "5",
"user_id": "9",
"question": "Trust in doctor's decision",
"type": "rating"
}
],
{
"user_id": "9",
"email_id": "user7#gmail.com",
"pass": "user7",
"address": "miraroad",
"name": "user7",
"survey_id": "35"
},
"",
[
{
"answer_id": "80",
"survey_id": "53",
"question_id": "1",
"rating": "5",
"user_id": "9",
"question": "Scheduling appointments",
"type": "rating"
},
{
"answer_id": "81",
"survey_id": "53",
"question_id": "7",
"rating": "5",
"user_id": "9",
"question": "Doctor listens and answers questions",
"type": "rating"
}
],
{
"user_id": "9",
"email_id": "user7#gmail.com",
"pass": "user7",
"address": "miraroad",
"name": "user7",
"survey_id": "35"
},
"",
[
{
"answer_id": "82",
"survey_id": "54",
"question_id": "6",
"rating": "5",
"user_id": "9",
"question": "Doctor explains medical condition(s)",
"type": "rating"
},
{
"answer_id": "83",
"survey_id": "54",
"question_id": "3",
"rating": "5",
"user_id": "9",
"question": "Staff helpfulness",
"type": "rating"
}
],
{
"user_id": "9",
"email_id": "user7#gmail.com",
"pass": "user7",
"address": "miraroad",
"name": "user7",
"survey_id": "35"
},
""
]
}
I am getting some what format same as I want. I am getting answers array, user and comment after that. But how I can name it? Can not identify from this result that where are answers, user and comment. I want to name it. How can I? Thank you.
You can simply create an associative array for each survey. Inside this associative array, assign your keys and your values. Here's how it looks :
function getAllSurveyByDoctor($user_id)
{
$database = new SurveyDatabase(SurveyConstants::DBHOST,SurveyConstants::DBUSER,SurveyConstants::DBPASS,SurveyConstants::DBNAME);
$dbConnection = $database->getDB();
$stmt = $dbConnection->prepare("SELECT * from survey where `user_id` = ?");
$stmt->execute(array($user_id));
$survey = $stmt->fetchAll(PDO::FETCH_ASSOC);
$surveys = array();
$answers = array();
if (count($survey) > 0) {
foreach($survey as $row)
{
$stmt = $dbConnection->prepare("SELECT answer.answer_id, answer.survey_id, answer.question_id, answer.rating, answer.user_id, question.question_id, question.question, question.type FROM `answer` INNER JOIN `question` ON
answer.question_id = question.question_id WHERE answer.user_id = ? and answer.survey_id = ?");
$s_id = $row['survey_id'];
$stmt->execute(array($user_id,$s_id));
$answer = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt = $dbConnection->prepare("SELECT users.user_id,users.email_id,users.pass,users.address,users.name,survey.survey_id,survey.user_id FROM `users` INNER JOIN `survey` ON users.user_id = survey.user_id WHERE users.user_id = ?");
$stmt->execute(array($user_id));
$user = $stmt->fetch(PDO::FETCH_ASSOC);
$comment = $row['comment'];
// $surveys[] = $row;
//We create the "survey" associative array
$survey = [];
$answers = $answer;
$survey['answers']= $answers;
$survey['user'] = $user;
$survey['comment']=$comment;
//We add the survey array to the survey
$surveys[] = $survey;
}
$response = array("status" => 1, "message" => "Success", "surveys" => $surveys);
return json_encode($response);
}
else {
$response = array("status"=>-1,"message"=>"surveys list is empty");
return json_encode($response);
}
}

Issue with json_decode and json_encode - it adds keys to original JSON

I have this JSON string:
{
"product": [
{
"id": "1",
"title": "producta",
"size": "50",
"weight": "1000",
"price": "30",
"quantity": "100",
"cartID": "1"
},
{
"id": "1",
"title": "producta",
"size": "50",
"weight": "1000",
"price": "30",
"quantity": "100",
"cartID": "2"
}
]
}
When I use the PHP function json_decode($products, true), and then I re-encode it using json_encode($products), the string becomes this:
{
"product": {
"1": {
"id": "2",
"title": "producta",
"size": "50",
"weight": "1000",
"price": "30",
"quantity": "100",
"cartID": "2"
},
"2": {
"id": "1",
"title": "producta",
"size": "50",
"weight": "1000",
"price": "30",
"quantity": "100",
"cartID": "3"
}
}
}
After decoding and re-encoding, it adds a key to every "product"
Is there a way around this?
Posting this here since it'd be too ugly in a comment, but this is what I get on PHP 5.3.6 after doing a echo json_encode(json_decode('...your json...', true));:
{"product": [
{"id":"1","title":"producta","size":"50","weight":"1000","price":"30","quantity":"100","cartID":"1"},
{"id":"1","title":"producta","size":"50","weight":"1000","price":"30","quantity":"100","cartID":"2"}
]}
Note the lack of extra keys. Are you doing any manipulations on the decoed array before re-encoding?
You are probably using mysqli_fetch_array instead of mysqli_fetch_assoc. Meaning u are json decoding a key arreay instead of an associative array

Categories