How to display the values from multidiamentional array - php

Here i have one array, from here i want display all values, but don't know how get all values from this array,i am new person of development any one know means please update my code.I spent lot of time but i am not able to find the exact answer
print_r($planMaster);
{
"status": "success",
"message": "Total 3 record(s) found.",
"total_record": 3,
"data": [
{
"planId": "1",
"planName": "Easy Plan",
"createdOn": "2017-10-23 15:17:08",
"createdBy": "Kani",
"updatedOn": "0000-00-00",
"updatedBy": "",
"planDescription": [
{
"descriptionId": "1",
"planId": "1",
"plandescTitle": "Contacts details up to",
"plandescResult": "24"
},
{
"descriptionId": "2",
"planId": "1",
"plandescTitle": "Bonus Contact details up to",
"plandescResult": "2"
},
{
"descriptionId": "3",
"planId": "1",
"plandescTitle": "Area Master Assistance",
"plandescResult": "No"
},
{
"descriptionId": "4",
"planId": "1",
"plandescTitle": "Contact details through sms",
"plandescResult": "Yes"
}
],
"planValue": [
{
"pvId": "2",
"planId": "1",
"startDate": "2017-10-23",
"endDate": "2017-10-30",
"planValue": "1000"
}
]
},
{
"planId": "2",
"planName": "Cool Plan",
"createdOn": "2017-10-23 16:58:32",
"createdBy": "Kani",
"updatedOn": "0000-00-00",
"updatedBy": "",
"planDescription": [
{
"descriptionId": "5",
"planId": "2",
"plandescTitle": "Contact details up to",
"plandescResult": "48"
},
{
"descriptionId": "6",
"planId": "2",
"plandescTitle": "Bonus Contact details up to",
"plandescResult": "4"
},
{
"descriptionId": "7",
"planId": "2",
"plandescTitle": "Area Master Assistance",
"plandescResult": "Yes"
},
{
"descriptionId": "8",
"planId": "2",
"plandescTitle": "Contact details through sms",
"plandescResult": "Yes"
}
],
"planValue": [
{
"pvId": "3",
"planId": "2",
"startDate": "2017-10-23",
"endDate": "2017-10-30",
"planValue": "2000"
}
]
},
{
"planId": "3",
"planName": "Free Plan",
"createdOn": "2017-10-23 17:09:20",
"createdBy": "Kani",
"updatedOn": "0000-00-00",
"updatedBy": "",
"planDescription": [
{
"descriptionId": "9",
"planId": "3",
"plandescTitle": "Contacts details up to",
"plandescResult": "5"
},
{
"descriptionId": "10",
"planId": "3",
"plandescTitle": "Area Master Assistance",
"plandescResult": "No"
},
{
"descriptionId": "11",
"planId": "3",
"plandescTitle": "Contact details through sms",
"plandescResult": "Yes"
}
],
"planValue": [
{
"pvId": "4",
"planId": "3",
"startDate": "2017-10-23",
"endDate": "2017-10-30",
"planValue": "0"
}
]
}
]
}
Expected Answer
Plan Name: Easy Plan
plandescTitle: Contacts details up to
plandescResult: 24
plandescTitle: Bonus Contact details up to
plandescResult": 2
I tried like this but not getting answer
<?php
$planMaster = GetResponse($API_URL.'getplan_Master');
if (!empty($planMaster)) {
foreach ($planMaster['data'] as $result) {
?>
<th><?php echo $result['planName']; ?> 1000/-</th>
<?php
foreach ($planMaster['planDescription'] as $descresult) {
echo $descresult['plandescTitle'];
}
?>
<?php
}
}
?>

Try this. I'll explain it if it works.
<?php
$planMaster = GetResponse($API_URL.'getplan_Master');
if (!empty($planMaster)) {
foreach ($planMaster['data'] as $result) {
?>
<th><?php echo $result['planName']; ?> 1000/-</th>
<?php
foreach ($result['planDescription'] as $descresult) {
echo $descresult['plandescTitle'];
}
?>
<?php
}
}
?>

you need to use json_decode() function to convert json data to php Array
$planMaster = GetResponse($API_URL.'getplan_Master');
$planMasterArray = json_decode($planMaster, true);
if (isset($planMasterArray) && is_array($planMasterArray)) {
foreach ($planMasterArray['data'] as $result) {
?>
<th><?php echo $result['planName']; ?> 1000/-</th>
<?php
foreach ($planMaster['planDescription'] as $descresult) {
echo $descresult['plandescTitle'];
}
?>
<?php
}
}
?>

Related

creating json file from database

I need to create this json in the following format
{
"status": true,
"message": "",
"orders": [
{
"orderId": "1",
"orderDate": "1/06/2021",
"products": [
{
"productName": "Product 1",
"quantity": "1",
"price": "5.00"
},
{
"productName": "Product 2",
"quantity": "2",
"price": "24.00"
},
{
"productName": "Product 3",
"quantity": "1",
"price": "6.50"
}
]
},
{
"orderId": "2",
"orderDate": "2/06/2021",
"products": [
{
"productName": "Product 1",
"quantity": "1",
"price": "3.00"
},
{
"productName": "Product 2",
"quantity": "1",
"price": "11.50"
}
]
},
{
"orderId": "3",
"orderDate": "03/05/2021",
"products": [
{
"productName": "Product 1",
"quantity": "1",
"price": "3.00"
},
{
"productName": "Product 2",
"quantity": "1",
"price": "11.50"
}
]
}
]
}
This is my code that I use to retrive the information from the database
$stmt = $con->prepare("SELECT OrderID, OrderDate, ProductName, ProductQty, ProductPrice FROM Orders where CustomerID = ?");
$stmt->bind_param("s", $CustomerID);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($OrderID, $OrderDate, $ProductName, $ProductQty, $ProductPrice);
while($stmt->fetch()) {
$message[] = array(
"status" => true,
"message" => "",
"orders" => array(
array(
"orderId" => "$OrderID",
"orderDate" => "$OrderDate",
"products" => array(
array(
"productName" => "$ProductName",
"quantity" => "$ProductQty",
"price" => "$ProductPrice"
),
)
)
)
);
}
$json = $message;
header('content-type: application/json');
echo json_encode($json);
This is how the information from the database displays. I do not know how to show the information about the products correctly. Can anyone show me how to do it in the format that I require in php? Thanks in advance for any help.
[
{
"status": true,
"message": "",
"orders": [
{
"orderId": "1",
"orderDate": "1/06/2021",
"products": [
{
"productName": "620",
"quantity": "1",
"price": "5.00"
}
]
}
]
},
{
"status": true,
"message": "",
"orders": [
{
"orderId": "1",
"orderDate": "1/06/2021",
"products": [
{
"productName": "240",
"quantity": "1",
"price": "5.00"
},
{
"productName": "270",
"quantity": "1",
"price": "10.00"
}
]
}
]
},
{
"status": true,
"message": "",
"orders": [
{
"orderId": "1",
"orderDate": "1/06/2021",
"products": [
{
"productName": "30",
"quantity": "1",
"price": "5.00"
}
]
}
]
},
{
"status": true,
"message": "",
"orders": [
{
"orderId": "1",
"orderDate": "1/06/2021",
"products": [
{
"productName": "280",
"quantity": "1",
"price": "5.00"
}
]
}
]
},
{
"status": true,
"message": "",
"orders": [
{
"orderId": "1",
"orderDate": "1/06/2021",
"products": [
{
"productName": "610",
"quantity": "1",
"price": "5.00"
}
]
}
]
}
]
You are repeating the orders structure which you shouldn't. That's why you get the wrong structure. This is what you should do instead (your code, modified):
// specify your return response array only once
$message = array(
"status" => true,
"message" => "",
"orders" => array();
);
$stmt = $con->prepare("SELECT OrderID, OrderDate, ProductName, ProductQty, ProductPrice FROM Orders where CustomerID = ?");
$stmt->bind_param("s", $CustomerID);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($OrderID, $OrderDate, $ProductName, $ProductQty, $ProductPrice);
while($stmt->fetch()) {
// and fill its "orders" member with your orders list
$message["orders"][] = array(
"orderId" => "$OrderID",
"orderDate" => "$OrderDate",
"products" => array(
array(
"productName" => "$ProductName",
"quantity" => "$ProductQty",
"price" => "$ProductPrice"
),
)
);
}
$json = $message;
header('content-type: application/json');
echo json_encode($json);
You can try like below
const data = [
{
"status": true,
"message": "",
"orders": [
{
"orderId": "1",
"orderDate": "1/06/2021",
"products": [
{
"productName": "620",
"quantity": "1",
"price": "5.00"
}
]
}
]
},
{
"status": true,
"message": "",
"orders": [
{
"orderId": "1",
"orderDate": "1/06/2021",
"products": [
{
"productName": "240",
"quantity": "1",
"price": "5.00"
},
{
"productName": "270",
"quantity": "1",
"price": "10.00"
}
]
}
]
},
{
"status": true,
"message": "",
"orders": [
{
"orderId": "1",
"orderDate": "1/06/2021",
"products": [
{
"productName": "30",
"quantity": "1",
"price": "5.00"
}
]
}
]
},
{
"status": true,
"message": "",
"orders": [
{
"orderId": "1",
"orderDate": "1/06/2021",
"products": [
{
"productName": "280",
"quantity": "1",
"price": "5.00"
}
]
}
]
},
{
"status": true,
"message": "",
"orders": [
{
"orderId": "1",
"orderDate": "1/06/2021",
"products": [
{
"productName": "610",
"quantity": "1",
"price": "5.00"
}
]
}
]
},
{
"status": false,
"message": "",
"orders": [
{
"orderId": "1",
"orderDate": "1/06/2021",
"products": [
{
"productName": "800",
"quantity": "50",
"price": "5.00"
}
]
}
]
},
{
"status": false,
"message": "",
"orders": [
{
"orderId": "1",
"orderDate": "1/06/2021",
"products": [
{
"productName": "1800",
"quantity": "50",
"price": "5.00"
}
]
}
]
}
];
const resutl = data.reduce((acc, cur) => {
const key = cur.status ? "successItems" : "failureItems";
if (acc[key]) {
return {
...acc,
[key]: {
status: cur.status,
messgae: '',
orders: [
...acc[key].orders,
...cur.orders
]
}
}
} else {
return {
...acc,
[key]: {
status: cur.status,
messgae: '',
orders: [
...cur.orders
]
}
}
}
}, {});
console.log('resutl', resutl);
console.log('resutl', Object.values(resutl));

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

Display some parts of a file written in json

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"
}]
}
}

How to merge two JSON under an Array in PHP

I get details from the user through HTML form, and onclick the form submission, I run the php file, save2json.php, which retrieves from HTML form, and posts it as JSON in the file appointments.json.
save2json.php
$formdata = array(
$_POST['doctor'] => array(
'name'=> $_POST['name'],
'phone'=> $_POST['phone'],
'bday'=> $_POST['bday'],
'datepicker'=> $_POST['datepicker'],
)
);
$filetxt = 'appointments.json';
$arr_data = array();
if(file_exists($filetxt))
{
$jsondata = file_get_contents($filetxt);
$arr_data = json_decode($jsondata, true);
}
$arr_data[] = $formdata;
$jsondata = json_encode($arr_data, JSON_PRETTY_PRINT);
if(file_put_contents('appointments.json', $jsondata))
What I get: [appointments.json]
[{
"Doctor #3": {
"name": "0",
"phone": "0",
"bday": "0",
"datepicker": "0"
}
}, {
"Doctor #3": {
"name": "1",
"phone": "1",
"bday": "1",
"datepicker": "1"
}
}, {
"Doctor #1": {
"name": "2",
"phone": "2",
"bday": "2",
"datepicker": "2"
}
}, {
"Doctor #2": {
"name": "3",
"phone": "3",
"bday": "3",
"datepicker": "3"
}
}]
What I want: [appointments.json]
[{
"Doctor #3": [{
"name": "0",
"phone": "0",
"bday": "0",
"datepicker": "0"
},
{
"name": "1",
"phone": "1",
"bday": "1",
"datepicker": "1"
}
],
"Doctor #1": {
"name": "2",
"phone": "2",
"bday": "2",
"datepicker": "2"
},
"Doctor #2": {
"name": "3",
"phone": "3",
"bday": "3",
"datepicker": "3"
}
}]
If it is under same doctor, I want to make both objects come under the same array. And if it isn't like Doctor 1 and Doctor 2, in this case, I want them as separate apart from Doctor 3 array.
Thanks in Advance :)
This is the first attempt to put it inside the doctor array key:
<?php
// build the array
$docDetails = array(
'name'=> $_POST['name'],
'phone'=> $_POST['phone'],
'bday'=> $_POST['bday'],
'datepicker'=> $_POST['datepicker'],
);
// get the file's content as an array.
$filetxt = 'appointments.json';
if(file_exists($filetxt))
$arr_data = json_decode(file_get_contents($filetxt), true);
else
$arr_data = array();
$arr_data[$_POST['doctor']][] = $docDetails;
?>

remove unnecessary hierarchy from json output

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"
}
]
}
]
}

Categories