This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 5 years ago.
{
"result": "success",
"clientid": "1",
"serviceid": null,
"pid": null,
"domain": null,
"totalresults": "2",
"startnumber": 0,
"numreturned": 2,
"products": {
"product": [
{
"id": "1",
"clientid": "1",
"orderid": "1",
"pid": "1",
"regdate": "2015-01-01",
"name": "Starter",
"translated_name": "Starter",
"groupname": "Shared Hosting",
"translated_groupname": "Shared Hosting",
"domain": "demodomain.com",
"dedicatedip": "",
"serverid": "1",
"servername": "Saturn",
"serverip": "1.2.3.4",
"serverhostname": "saturn.example.com",
"suspensionreason": "",
"firstpaymentamount": "12.95",
"recurringamount": "12.95",
"paymentmethod": "authorize",
"paymentmethodname": "Credit Card",
"billingcycle": "Monthly",
"nextduedate": "2016-11-25",
"status": "Terminated",
"username": "demodoma",
"password": "xxxxxxxx",
"subscriptionid": "",
"promoid": "0",
"overideautosuspend": "",
"overidesuspenduntil": "0000-00-00",
"ns1": "",
"ns2": "",
"assignedips": "",
"notes": "",
"diskusage": "0",
"disklimit": "0",
"bwusage": "0",
"bwlimit": "0",
"lastupdate": "0000-00-00 00:00:00",
"customfields": {
"customfield": []
},
"configoptions": {
"configoption": []
}
},
{
"id": "2",
"clientid": "1",
"orderid": "2",
"pid": "3",
"regdate": "2015-05-20",
"name": "Plus",
"translated_name": "Plus",
"groupname": "Shared Hosting",
"translated_groupname": "Shared Hosting",
"domain": "demodomain2.net",
"dedicatedip": "",
"serverid": "2",
"servername": "Pluto",
"serverip": "2.3.4.5",
"serverhostname": "pluto.example.com",
"suspensionreason": "",
"firstpaymentamount": "24.95",
"recurringamount": "24.95",
"paymentmethod": "paypal",
"paymentmethodname": "PayPal",
"billingcycle": "Monthly",
"nextduedate": "2017-01-20",
"status": "Active",
"username": "demodom2",
"password": "xxxxxxxx",
"subscriptionid": "",
"promoid": "0",
"overideautosuspend": "",
"overidesuspenduntil": "0000-00-00",
"ns1": "",
"ns2": "",
"assignedips": "",
"notes": "",
"diskusage": "0",
"disklimit": "0",
"bwusage": "0",
"bwlimit": "0",
"lastupdate": "0000-00-00 00:00:00",
"customfields": {
"customfield": []
},
"configoptions": {
"configoption": [
{
"id": "1",
"option": "Sample Config Option",
"type": "dropdown",
"value": "Selected option value"
}
]
}
}
]
}
}
How can i parse the product details from json
You can use json decode function of php to make object then fetch data from object.
$data = 'write your json response here';
$return = json_decode($data);
print_r($return);
echo $return->result;
Related
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"
}
}
]
}]
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
I need help, we have already developed 500+ web-services for the current project, i don't want to modify all the web-services, can any help me how to replace null with " " double quotes for json output in php using output buffer..
Actual Output came
{
"err_code": "valid",
"title": "",
"message": "User details",
"data": {
"fullname": "Vijay Kumarr",
"mobile": "4564564564654",
"token": "OGUBXtyxDARNISJGOlQu",
"customer_meta": {
"id": "6",
"customers_id": "6",
"email": "xyz#abc.com",
"alternative_mobile": null,
"door_no": "1-2/3",
"street_name": "Street",
"location_name": "Locationn",
"city_name": "vizag",
"district_name": "Vizag",
"state_name": "Andhra Pradesh",
"zipcode": "530016",
"countries_id": "1",
"gst_number": null,
"aadhar_number": null,
"pan_number": null,
"created_at": "1522060789",
"updated_at": "1522484859",
"status": "1"
}
}
}
I am expecting Output as
{
"err_code": "valid",
"title": "",
"message": "User details",
"data": {
"fullname": "Vijay Kumarr",
"mobile": "4564564564654",
"token": "OGUBXtyxDARNISJGOlQu",
"customer_meta": {
"id": "6",
"customers_id": "6",
"email": "xyz#abc.com",
"alternative_mobile": "",
"door_no": "1-2/3",
"street_name": "Street",
"location_name": "Locationn",
"city_name": "vizag",
"district_name": "Vizag",
"state_name": "Andhra Pradesh",
"zipcode": "530016",
"countries_id": "1",
"gst_number": "",
"aadhar_number": "",
"pan_number": "",
"created_at": "1522060789",
"updated_at": "1522484859",
"status": "1"
}
}
}
This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 9 years ago.
In CodeIgniter, in PHP to create a nested-like elements for dropdown <select> I'am using this function:
function list_categories(&$result, $cats, $sub = ''){ // <- THIS
foreach($cats as $cat){
//$cat['category']->id = $sub.$cat['category']->title;
$result[$cat['category']->id] = $sub.$cat['category']->title; // <- THIS
if( sizeof($cat['children']) > 0 ){
$sub2 = str_replace('—→ ', '–', $sub);
$sub2.= '–→ ';
list_categories($result, $cat['children'], $sub2); // <- THIS
}
}
}
// Make an array available outside the function
$categoryData = array(0 => '-- '.lang('FORM_SELECT_CATTOP').' --');
// Launch the function to fill out the array with nested sets
list_categories($categoryData, $categories);
Which generates the HTML <select> list:
I want to do the same from retrieved JSON in jQuery but can't find the answer to go deeper than first level of JSON objects with this jQuery function:
$.getJSON('../raw_get_categories/'+com_id_selected+'/0', function(data){
var items = [];
$.each(data, function(key, value, sub){
items.push('<option id="'+ key[0] + '">' + value[0] + '</option>');
});
console.log(items);
});
And this is the JSON I want to manage and retrieve the same values from it like in PHP code:
{
"28": {
"category": {
"id": "28", // <<< I need to retrieve THIS
"pid": "0",
"com_id": "2",
"route_id": "59",
"excerpt": "",
"ordering": "1",
"title": "Oblecenie a vybava",
"slug": "oblecenie-a-vybava1",
"description": "",
"image": "clothes.png",
"seo_title": "",
"meta": ""
},
"compname": {
"id": "2",
"name": "E-commerce"
},
"children": {
"61": {
"category": {
"id": "61", // <<< I need to retrieve THIS
"pid": "28",
"com_id": "2",
"route_id": "52",
"excerpt": "",
"ordering": "1",
"title": "Ubor na hlavu",
"slug": "ubor-na-hlavu1",
"description": "<p>Capice, Klobuky, Panamy, Baretky, Prilby, Kukly<br></p>",
"image": "clothes-head.png",
"seo_title": "",
"meta": ""
},
"compname": {
"id": "2",
"name": "E-commerce"
},
"children": [ ]
},
"30": {
"category": {
"id": "30",
"pid": "28",
"com_id": "2",
"route_id": "53",
"excerpt": "",
"ordering": "2",
"title": "Bundy a vetrovky",
"slug": "bundy-a-vetrovky",
"description": "",
"image": "",
"seo_title": "",
"meta": ""
},
"compname": {
"id": "2",
"name": "E-commerce"
},
"children": {
"34": {
"category": {
"id": "34",
"pid": "30",
"com_id": "2",
"route_id": "0",
"excerpt": "",
"ordering": "0",
"title": "Letne",
"slug": "letne",
"description": "",
"image": "",
"seo_title": "",
"meta": ""
},
"compname": {
"id": "2",
"name": "E-commerce"
},
"children": [ ]
},
"35": {
"category": {
"id": "35",
"pid": "30",
"com_id": "2",
"route_id": "0",
"excerpt": "",
"ordering": "0",
"title": "Vsesezonne",
"slug": "vsesezonne",
"description": "",
"image": "",
"seo_title": "",
"meta": ""
},
"compname": {
"id": "2",
"name": "E-commerce"
},
"children": [ ]
},
"33": {
"category": {
"id": "33",
"pid": "30",
"com_id": "2",
"route_id": "0",
"excerpt": "",
"ordering": "0",
"title": "Zimne",
"slug": "zimne",
"description": "",
"image": "",
"seo_title": "",
"meta": ""
},
"compname": {
"id": "2",
"name": "E-commerce"
},
"children": [ ]
}
}
},
"31": {
"category": {
"id": "31",
"pid": "28",
"com_id": "2",
"route_id": "54",
"excerpt": "",
"ordering": "3",
"title": "Nohavice a teplaky",
"slug": "nohavice-a-teplaky",
"description": "",
"image": "",
"seo_title": "",
"meta": ""
},
"compname": {
"id": "2",
"name": "E-commerce"
},
"children": [ ]
},
"32": {
"category": {
"id": "32",
"pid": "28",
"com_id": "2",
"route_id": "55",
"excerpt": "",
"ordering": "4",
"title": "Obuv",
"slug": "obuv",
"description": "",
"image": "",
"seo_title": "",
"meta": ""
},
"compname": {
"id": "2",
"name": "E-commerce"
},
"children": [ ]
}
}
},
"38": {
...
}
Could someone suggest me the appropriate way to achieve the same foreach statement in jQuery pls?
Juste use point to get more childs
$.getJSON('filename.php', function(data) {
$('#List li').remove();
$.each(data, function(index, item) {
$('#list').append('<li>'+item.category.id+'</li>');
});
});
You can do something like this:
$.each(data.actions, function(entryIndex, entry) {
var html = '<li class="top-level">' + this.action + '</li>';
});
Source
I have this JSON code:
{
"phrases": [
{
"phrases": [
{
"id": "33",
"text": "sasdsad",
"date": "2012-03-14 20:28:45",
"views": "0",
"ip": "64.191.90.5",
"reported": "0",
"strange": "0",
"lang": "en"
},
{
"id": "32",
"text": "que ondaa\r\n",
"date": "2012-03-14 20:27:45",
"views": "0",
"ip": "64.191.90.5",
"reported": "0",
"strange": "0",
"lang": "en"
},
{
"id": "31",
"text": "dsadssadsad",
"date": "2012-03-14 20:27:35",
"views": "0",
"ip": "64.191.90.5",
"reported": "0",
"strange": "0",
"lang": "en"
}
],
"details": {
"success": "true",
"phrase_id": "",
"phrase_text": "",
"phrase_date": ""
}
}
I don't really know what to do. I get some phrases vía MySQL, and pushes them to an array. This array is json_encoded() and gets printed.
$sth = $sql;
$rows = array();
while($r = mysql_fetch_assoc($sth)) {
$rows[] = $r;
}
$sth = $sql;
$data = array(
"success" => "true",
"phrase_id" => "",
"phrase_text" => "",
"phrase_date" => "",
);
print json_encode($rows).json_encode($data);
and with jQuery I was trying to parse it, but I can't. This is the main problem.
function getPhrases(order,limit,last){
var req_url = ...;
$.getJSON(req_url, function(data) {
$.each(data.phrases, function(i, data) {
appendPhrase(data.text);
lastid = data.id;
});
$.each(data.details, function(i, data) {
$("#phrases-count").html(data.totalcount);
});
});
}
PS: I was doing this with "echo" but got some problems.
{
"phrases": [
{
"id": "33",
"text": "sasdsad",
"date": "2012-03-14 20:28:45",
"views": "0",
"ip": "64.191.90.5",
"lang": "en"
},
{
"id": "32",
"text": "que ondaa<br />",
"date": "2012-03-14 20:27:45",
"views": "0",
"ip": "64.191.90.5",
"lang": "en"
},
{
"id": "31",
"text": "dsadssadsad",
"date": "2012-03-14 20:27:35",
"views": "0",
"ip": "64.191.90.5",
"lang": "en"
}
],
"details": [
{
"totalcount": "3",
"logged_in": "false"
}
]
}
You can't simply combine these JSON arrays:
print json_encode($rows).json_encode($data);
Try this (attempt 2):
print json_encode( array('phrases' => $rows, 'details' => $data) );