How do I process this JSONArray?
I receive it through a POST from an Android app.
"[
"Itemz",
{
"id": "1",
"idviz": "3",
"pux": "100.00",
"umx": "PCS",
"cantx": "3",
"name": "Item 1 name"
},
"Itemz",
{
"id": "3",
"idviz": "3",
"pux": "230.00",
"umx": "PCS",
"cantx": "2",
"name": "Item 2 name"
},
"Itemz",
{
"id": "7",
"idviz": "3",
"pux": "87.23",
"umx": "LTR",
"cantx": "6",
"name": "Item 3 name"
}
]"
How do I access the items inside this JSON Array?
I need to break it apart so I can build mysql insert statements. As you can assume each "Items" is an Item that must be inserted in a table.
Thank you
json_decode
will parse the json string into an array
There is an extra quote at the beginning and end of yones answer in the json, and also an extra double quote at the beginning and end of the OPs json. Since json uses double quotes, you need to encapsulate the entire json string in single quotes. Try this:
$json = '[
"Itemz",
{
"id": "1",
"idviz": "3",
"pux": "100.00",
"umx": "PCS",
"cantx": "3",
"name": "Item 1 name"
},
"Itemz",
{
"id": "3",
"idviz": "3",
"pux": "230.00",
"umx": "PCS",
"cantx": "2",
"name": "Item 2 name"
},
"Itemz",
{
"id": "7",
"idviz": "3",
"pux": "87.23",
"umx": "LTR",
"cantx": "6",
"name": "Item 3 name"
}
]';
echo '<pre>';
print_r(json_decode($json));
echo '</pre>';
Related
I have an object of json type column in my table (properties) in MySQL like:
[
{
"unit": "2",
"floor": "1",
"price": "6000000",
"toilet": "2",
"balcony": "2",
"bedrooms": "2",
"customer": "3",
"bathrooms": "3",
"flat_name": "1A",
"flat_size": "1200",
"floor_plan": "217",
"price_per_sqft": "5000"
},
{
"unit": "2",
"floor": "1",
"price": "5000000",
"toilet": "2",
"balcony": "2",
"bedrooms": "2",
"customer": null,
"bathrooms": "3",
"flat_name": "1B",
"flat_size": "1200",
"floor_plan": "215",
"price_per_sqft": "5000"
},
{
"unit": "1",
"floor": "2",
"price": "6000000",
"toilet": "2",
"balcony": "2",
"bedrooms": "2",
"customer": null,
"bathrooms": "3",
"flat_name": "2A",
"flat_size": "1250",
"floor_plan": "216",
"price_per_sqft": "5300"
}
]
How can I update customer id, where flat_name = 1B from this object in Laravel?
I have made the solution with using loop. Thank you who reply and answer
$objectitem=Property::where("id", 1)->first();
$updatedFlatDetails= $objectitem->flat_details;
foreach ($objectitem->flat_details as $key => $singleflat){
if($singleflat['flat_name']==$item->flat_name){
$updatedFlatDetails[$key]['customer']=(string)$item->customer_id;
}
}
$objectitem->flat_details = $updatedFlatDetails;
$objectitem->save();
Use collection after fetch data from database :
$target= $collection->filter(function ($item) {
return $item->flat_name=="1B";
})->values();
or filter before fetch data use eloquent :
Model::where('flat_name','1B')->get();
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 am trying to get JSON from an array but I am getting an extra square bracket in the output.
I tried using $episode[0] = $podcast->getPodcastByCategoryId($id); but it only gives the incomplete output means it gives data of the first iteration from the array. And if I remove [] from $episode that also gives the data of first iteration.
$podList = $category->getCategoryPodcast();
if ($podList) {
foreach ($podList as $items) {
$id = $items->id;
$episode[] = $podcast->getPodcastByCategoryId($id);
}
}
echo json_encode($episode);
I expect to have only one square bracket but I am getting the output with two square brackets.
This is the out I am receiving from the above code:
[
[
{
"id": "6",
"title": "Types of loops in PHP.",
"description": "s.kfjhsdlufdgf o",
"duration": "0:05:05",
"audio": "http://demo.web/uploads/podAudio/PodAudio-2019011511270942.mp3",
"image": "http://demo.web/uploads/podImage/PodImage-20190115112709469.jpg",
"category": "2",
"added_date": "माघ १, २०७५",
"category_title": "उमेर",
"author": "John Doe",
"episodes": "2"
},
{
"id": "4",
"title": "How to remove square brackets from JSON?",
"description": "",
"duration": "",
"audio": "http://demo.web/uploads/podAudio/PodAudio-20190114111541297.mp3",
"image": "http://demo.web/uploads/podImage/PodImage-20190114102432145.jpg",
"category": "2",
"added_date": "पौष ३०, २०७५",
"category_title": "उमेर",
"author": "John Doe",
"episodes": "2"
}
],
[
{
"id": "5",
"title": "Hello World!",
"description": "",
"duration": "",
"audio": "http://demo.web/uploads/podAudio/PodAudio-20190114111937115.mp3",
"image": "http://demo.web/uploads/podImage/PodImage-20190114104302103.jpg",
"category": "1",
"added_date": "पौष ३०, २०७५",
"category_title": "गृह पृष्ठ",
"author": "John Doe",
"episodes": "1"
}
]
]
According to the recommendation from #splash58 and #Vinesh Goyal, I am getting output like this:
[[
{
"id": "6",
"title": "Types of loops in PHP.",
"description": "s.kfjhsdlufdgf o",
"duration": "0:05:05",
"audio": "http://demo.web/uploads/podAudio/PodAudio-2019011511270942.mp3",
"image": "http://demo.web/uploads/podImage/PodImage-20190115112709469.jpg",
"category": "2",
"added_date": "माघ १, २०७५",
"category_title": "उमेर",
"author": "John Doe",
"episodes": "2"
},
{
"id": "4",
"title": "How to remove square brackets from JSON?",
"description": "",
"duration": "",
"audio": "http://demo.web/uploads/podAudio/PodAudio-20190114111541297.mp3",
"image": "http://demo.web/uploads/podImage/PodImage-20190114102432145.jpg",
"category": "2",
"added_date": "पौष ३०, २०७५",
"category_title": "उमेर",
"author": "John Doe",
"episodes": "2"
}
],
{
"id": "5",
"title": "Hello World!",
"description": "",
"duration": "",
"audio": "http://demo.web/uploads/podAudio/PodAudio-20190114111937115.mp3",
"image": "http://demo.web/uploads/podImage/PodImage-20190114104302103.jpg",
"category": "1",
"added_date": "पौष ३०, २०७५",
"category_title": "गृह पृष्ठ",
"author": "John Doe",
"episodes": "1"
}
]
but, what about the square brackets of first data?
You can merge arrays while getting
$episode = array_merge($episode, $podcast->getPodcastByCategoryId($id));
Or flatten the result array before converting to json
echo json_encode(array_merge(...$episode));
demo
Following snippet using javascript .concat() . Does this fit your desired output?
var data = [[
{
"id": "6",
"title": "Types of loops in PHP.",
"description": "s.kfjhsdlufdgf o",
"duration": "0:05:05",
"audio": "http://demo.web/uploads/podAudio/PodAudio-2019011511270942.mp3",
"image": "http://demo.web/uploads/podImage/PodImage-20190115112709469.jpg",
"category": "2",
"added_date": "माघ १, २०७५",
"category_title": "उमेर",
"author": "John Doe",
"episodes": "2"
},
{
"id": "4",
"title": "How to remove square brackets from JSON?",
"description": "",
"duration": "",
"audio": "http://demo.web/uploads/podAudio/PodAudio-20190114111541297.mp3",
"image": "http://demo.web/uploads/podImage/PodImage-20190114102432145.jpg",
"category": "2",
"added_date": "पौष ३०, २०७५",
"category_title": "उमेर",
"author": "John Doe",
"episodes": "2"
}
],
[
{
"id": "5",
"title": "Hello World!",
"description": "",
"duration": "",
"audio": "http://demo.web/uploads/podAudio/PodAudio-20190114111937115.mp3",
"image": "http://demo.web/uploads/podImage/PodImage-20190114104302103.jpg",
"category": "1",
"added_date": "पौष ३०, २०७५",
"category_title": "गृह पृष्ठ",
"author": "John Doe",
"episodes": "1"
}
]
];
var mergedData = data[0].concat(data[1]);
console.log(mergedData)
according to your code, $podcast->getPodcastByCategoryId($id); returning a array so t0 remove the issue you can use array_merge function
$podList = $category->getCategoryPodcast();
$episode = [];
if ($podList) {
foreach ($podList as $items) {
$id = $items->id;
$episode = array_merge($episode, $podcast->getPodcastByCategoryId($id)
}
}
echo json_encode($episode);
I hope it will help you :)
I have wcf web service returns daily news in json object which i convert to associative array, and i want to loop through this array to get certain data depending on some conditions (like get array when its date field = today and ignore the other data with another dates).
So I need to know how I can loop through the main array and divided it with conditions to finally get needed data.
Or if there is any other method to loop through the json object without converting to associative array?
Here is the array structure:
{"GetDailyNewsResult":
{
"IsError": false,
"ErrorMsg": "",
"DailyNews": [
{
"Date": "2016-04-18",
"LanguageID": "2",
"OuterTopic": "5",
"ReminderSectionID": "3",
"ReminderPhraseNo": "2",
"DailyNewsSections": [
{
"SectionID": "1",
"Header": "test",
"PhraseNo": "1",
"Phrase": "sergbsvbzxcvbcgh",
}
{
"SectionID": "2",
"Header": "test",
"PhraseNo": "2",
"Phrase": "fghdfyhdfgnbxc",
}
{
"SectionID": "3",
"Header": "test",
"PhraseNo": "3",
"Phrase": "dfeasertadsrtg",
}
{
"SectionID": "4",
"Header": "test",
"PhraseNo": "4",
"Phrase": "dfgbzxcvzxcv",
}
{
"SectionID": "5",
"Header": "test",
"PhraseNo": "5",
"Phrase": "sghdfgbxcvb",
}
{
"SectionID": "6",
"Header": "test",
"PhraseNo": "6",
"Phrase": "sdfagdvbxcvb",
}
{
"SectionID": "7",
"Header": "test",
"PhraseNo": "7",
"Phrase": "asdasdasd",
}
]
},
{
"Date": "2016-04-19",
"LanguageID": "2",
"OuterTopic": "5",
"ReminderSectionID": "3",
"ReminderPhraseNo": "2",
"DailyNewsSections": [
{
"SectionID": "1",
"Header": "test",
"PhraseNo": "1",
"Phrase": "jhmdfadrtgdfgfgh",
}
{
"SectionID": "2",
"Header": "test",
"PhraseNo": "2",
"Phrase": "asdfretfncvb",
}
{
"SectionID": "3",
"Header": "test",
"PhraseNo": "3",
"Phrase": "asdfgvbnvbn",
}
{
"SectionID": "4",
"Header": "test",
"PhraseNo": "4",
"Phrase": "dfghfgrrthsdvbc",
}
{
"SectionID": "5",
"Header": "test",
"PhraseNo": "5",
"Phrase": "dghdfghdfgh",
}
{
"SectionID": "6",
"Header": "test",
"PhraseNo": "6",
"Phrase": "ghdgfhdfgh",
}
{
"SectionID": "7",
"Header": "test",
"PhraseNo": "7",
"Phrase": "dfghdfghfdgh",
}
]
},
]
}
Do you need to keep the data as JSON Object? If you turn it into a json_decode($json, true)); you could loop through the data just as you would with any other array.
If you want to know how to loop through the array please provide more info about the data structure and what you want to do with it.
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