How to merge two JSON under an Array in PHP - 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;
?>

Related

Is there way to parse JSON like this from MySQL

I want to create a PHP API from server to parse JSON to Android
but never mind of that.
The main problem is how can I code this
This is my PHP code
<?php
include 'includes/conn.php';
$sql = "SELECT * FROM positions ORDER BY priority ASC";
$res = array();
$query = $conn->query($sql);
while($row = $query->fetch_assoc()){
$csql = "SELECT * FROM candidates WHERE position_id='".$row['id']."'";
$cquery = $conn->query($csql);
$cs = array(
'pos_id' => $row['id'],
'pos_des' => $row['description'],
'max_votes' => $row['max_vote']);
while($crow = $cquery->fetch_assoc()){
$fe = array(
'candidates' => array(
'id' => $crow['id'],
'pos_id' => $crow['position_id'],
'firstname' => $crow['firstname'],
'lastname' => $crow['lastname'],
'photo' => $crow['photo'],
'platform' => $crow['platform']
array_push($cs,fe);
)
);
}
array_push($res,$cs);
}
echo json_encode($res);
?>
Now its working fine but instead
of this
[{
"pos_id": "1",
"pos_des": "Reprisentative",
"max_votes": "4",
"candidates": {
"id": "1",
"pos_id": "1",
"firstname": "G-9-JAY",
"lastname": "MCARTHUR",
"photo": "",
"platform": ""
}
},
{
"pos_id": "1",
"pos_des": "Reprisentative",
"max_votes": "4",
"candidates": {
"id": "2",
"pos_id": "1",
"firstname": "G-10-JOHN",
"lastname": "MARTIN",
"photo": "",
"platform": ""
}
},
{
"pos_id": "1",
"pos_des": "Reprisentative",
"max_votes": "4",
"candidates": {
"id": "5",
"pos_id": "1",
"firstname": "GRADE 7",
"lastname": "Lang ya",
"photo": "",
"platform": ""
}
},
{
"pos_id": "2",
"pos_des": "President",
"max_votes": "1",
"candidates": {
"id": "3",
"pos_id": "2",
"firstname": "User",
"lastname": "Name",
"photo": "",
"platform": ""
}
},
{
"pos_id": "2",
"pos_des": "President",
"max_votes": "1",
"candidates": {
"id": "4",
"pos_id": "2",
"firstname": "TEST",
"lastname": "USER",
"photo": "",
"platform": ""
}
}
]
I want this result
[{
"pos_id": "1",
"pos_des": "Reprisentative",
"max_votes": "4",
"candidates": [{
"id": "1",
"pos_id": "1",
"firstname": "G-9-JAY",
"lastname": "MCARTHUR",
"photo": "",
"platform": ""
}, {
"id": "2",
"pos_id": "1",
"firstname": "G-10-JOHN",
"lastname": "MARTIN",
"photo": "",
"platform": ""
}, {
"id": "5",
"pos_id": "1",
"firstname": "GRADE 7",
"lastname": "Lang ya",
"photo": "",
"platform": ""
}]
},
{
"pos_id": "2",
"pos_des": "President",
"max_votes": "1",
"candidates": [{
"id": "3",
"pos_id": "2",
"firstname": "User",
"lastname": "Name",
"photo": "",
"platform": ""
}, {
"id": "4",
"pos_id": "2",
"firstname": "TEST",
"lastname": "USER",
"photo": "",
"platform": ""
}]
}
]
Summary: I want The user to place in what pos_id he/she assign to the positions for example MARTIN is a running in president so MARTIN should show in President Position
How can I achieve this?
you should push onto $cs['candidates'], not create a separate array with candidates as the key for each candidate.
$cs = array(
'pos_id' => $row['id'],
'pos_des' => $row['description'],
'max_votes' => $row['max_vote'],
'candidates' => array());
while($crow = $cquery->fetch_assoc()){
$cs['candidates'][] = array(
'id' => $crow['id'],
'pos_id' => $crow['position_id'],
'firstname' => $crow['firstname'],
'lastname' => $crow['lastname'],
'photo' => $crow['photo'],
'platform' => $crow['platform']
);
}

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 get parent array element in PHP with recursive function

I have PHP code as shown below which will print:
id:3deep:2path:image31.jpg
id:4deep:2path:image32.jpg
when I input deep = 2. However I would like to get parent array of this deep which is id = 2. Is there any way that I can do this?
Note:
Please see the result when I input deep as below:
> Deep = 1
ID = 0
ID = 1
ID = 2
ID = 7
ID = 8
> Deep = 2
ID = 2
ID = 3
ID = 4
> Deep = 3
ID = 4
ID = 5
ID = 6
Please check my code online.
PHP:
$obj = '{
"images": {
"deep": "1",
"id": "0",
"path": "image1.jpg",
"image": [
{
"deep": "1",
"id": "1",
"coordinate": "(x,y),(x,y)",
"path": "image2.jpg"
},
{
"deep": "1",
"id": "2",
"coordinate": "(x,y),(x,y)",
"path": "image3.jpg",
"image": [
{
"deep": "2",
"id": "3",
"coordinate": "(x,y),(x,y)",
"path": "image31.jpg"
},
{
"deep": "2",
"id": "4",
"coordinate": "(x,y),(x,y)",
"path": "image32.jpg",
"image": [
{
"deep": "3",
"id": "5",
"coordinate": "(x,y),(x,y)",
"path": "image321.jpg"
},
{
"deep": "3",
"id": "6",
"coordinate": "(x,y),(x,y)",
"path": "image322.jpg"
}
]
}
]
},
{
"deep": "1",
"id": "7",
"coordinate": "(x,y),(x,y)",
"path": "image4.jpg"
},
{
"deep": "1",
"id": "8",
"coordinate": "(x,y),(x,y)",
"path": "image5.jpg"
}
]
}
}';
$objArray = json_decode($obj,true);
$deep = 2;
$arr = all($objArray['images'], $deep);
display($arr);
function all($a, $d){
$temp = array();
if(is_array($a)){
foreach($a as $v){
all($v, $d);
}
if(isset($a['deep']) && $d == $a['deep']){
$temp['id'] = $a['id'];
$temp['deep'] = $a['deep'];
$temp['path'] = $a['path'];
$s =
'id:'.$a['id'].
'deep:'.$a['deep'].
'path:'.$a['path'];
display($s);
}
}
return ;
}
function display($a){
echo "<pre>";
print_r($a);
echo "</pre>";
}
Idk exactly what you want, but I changed your code a bit to filter in a nicer way and it adds the parent key to each $image so you can reference that afterwards.
You can set the $deep = null paramater to just add the parent to the image instead of filtering.
I hope you don't mind I changed the code style a bit, easier to read ( I hope :D )
Here's the code within phpfiddle: http://phpfiddle.org/main/code/8q0-c43
<?php
$obj = '{
"images": {
"deep": "1",
"id": "0",
"path": "image1.jpg",
"image": [
{
"deep": "1",
"id": "1",
"coordinate": "(x,y),(x,y)",
"path": "image2.jpg"
},
{
"deep": "1",
"id": "2",
"coordinate": "(x,y),(x,y)",
"path": "image3.jpg",
"image": [
{
"deep": "2",
"id": "3",
"coordinate": "(x,y),(x,y)",
"path": "image31.jpg"
},
{
"deep": "2",
"id": "4",
"coordinate": "(x,y),(x,y)",
"path": "image32.jpg",
"image": [
{
"deep": "3",
"id": "5",
"coordinate": "(x,y),(x,y)",
"path": "image321.jpg"
},
{
"deep": "3",
"id": "6",
"coordinate": "(x,y),(x,y)",
"path": "image322.jpg"
}
]
}
]
},
{
"deep": "1",
"id": "7",
"coordinate": "(x,y),(x,y)",
"path": "image4.jpg"
},
{
"deep": "1",
"id": "8",
"coordinate": "(x,y),(x,y)",
"path": "image5.jpg"
}
]
}
}';
$objArray = json_decode($obj, true);
function filter_deep(array $input, $deep = null, $parent = null) {
// store $results so we can return it
$result = array();
// loop over the $input
foreach ($input as $image) {
// set the parent passed alogn
$image['parent'] = $parent;
// add $image to $result if 'deep' == $deep
if ($deep === null || $image['deep'] == $deep) {
$result[] = $image;
}
// if the $image contains more child images recursively run this function again
// and merge the result with what we already have
if (isset($image['image']) && is_array($image['image'])) {
$result = array_merge($result, filter_deep($image['image'], $deep, $image));
}
}
return $result;
}
function display_image($image) {
return "id:{$image['id']} deep:{$image['deep']} path:{$image['path']} parent_id:{$image['parent']['id']} <br />\n";
}
// loop over the images that have deep == 2 and display them
foreach (filter_deep(array($objArray['images']), 2) as $image) {
echo display_image($image);
}
?>

JSON decoding array

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) );

Categories