Hi am new to this topic and I really need a help from you who really know about this.
Below image shows my db design and query with results.
Following code is that I've tried so far.
<?php
include_once './DbConnect.php';
$db = new DbConnect();
$response = array();
$response["content_info"] = array();
$query = "SELECT Aid, AName, Bid, BName, Cid, CName, Content FROM A, B, C WHERE fk_Aid = Aid AND fk_Bid = Bid";
$result = mysqli_query($db->getConnection(),$query);
while($row = mysqli_fetch_array($result)){
$tmp = array();
$tmp["Aid"] = $row["Aid"];
$tmp["AName"] = $row["AName"];
$tmp["Bid"] = $row["Bid"];
$tmp["BName"] = $row["BName"];
$tmp["Cid"] = $row["Cid"];
$tmp["CName"] = $row["CName"];
$tmp["Content"] = $row["Content"];
// push info to final json array
array_push($response["content_info"], $tmp);
}
header('Content-Type: application/json');
echo json_encode($response);
?>
But it returns following JSON Object:
{
"content_info": [
{
"Aid": "A1",
"AName": "AName1",
"Bid": "B1",
"BName": "BName1",
"Cid": "C1",
"CName": "CName1",
"Content": "aaaaaaa"
},
{
"Aid": "A1",
"AName": "AName1",
"Bid": "B1",
"BName": "BName1",
"Cid": "C2",
"CName": "CName2",
"Content": "abdsdsfdsf"
},
{
"Aid": "A1",
"AName": "AName1",
"Bid": "B2",
"BName": "BName2",
"Cid": "C3",
"CName": "CName3",
"Content": "dfefeeefeee"
},
{
"Aid": "A1",
"AName": "AName1",
"Bid": "B2",
"BName": "BName2",
"Cid": "C4",
"CName": "CName4",
"Content": "fdsfdfdsf"
},
{
"Aid": "A2",
"AName": "AName2",
"Bid": "B3",
"BName": "BName3",
"Cid": "C5",
"CName": "CName5",
"Content": "fsdfsfsfddf"
}
]
}
But This is not the JSON object that I am expected. Following structure is the that I wanted
{
"content_info": [
{
"Aid": "A1",
"AName": "AName1",
"B": [
{
"Bid": "B1",
"BName": "BName1",
"C": [
{
"Cid": "C1",
"CName": "CName1",
"Content": "aaaaaaa"
},
{
"Cid": "C2",
"CName": "CName2",
"Content": "abdsdsfdsf"
}
]
},
{
"Bid": "B2",
"BName": "BName2",
"C": [
{
"Cid": "C3",
"CName": "CName3",
"Content": "dfefeeefeee"
},
{
"Cid": "C4",
"CName": "CName4",
"Content": "fdsfdfdsf"
}
]
}
]
},
{
"Aid": "A2",
"AName": "AName2",
"B": [
{
"Bid": "B3",
"BName": "BName3",
"C": [
{
"Cid": "C5",
"CName": "CName5",
"Content": "fsdfsfsfddf"
}
]
}
]
Please If someone knows could you please tell me what should I need to edit.
Thank You anyone who try for this.
while($row = mysqli_fetch_array($result)){
$tmp = array();
$tmp["Aid"] = $row["Aid"];
$tmp["AName"] = $row["AName"];
$tmp["B"] = array();
$query1 = "select * from B where fk_Aid= ".$row["Aid"];
$result1 = mysqli_query($db->getConnection(),$query1);
if($result1){
while($row1 = mysqli_fetch_array($result1)){
$tmp1 = array();
$tmp1["Bid"] = $row1["Bid"];
$tmp1["BName"] = $row1["BName"];
$tmp1["C"] = array();
$query2 = "select * from C where fk_Bid = ".$row1["Bid"];
$result2 = mysqli_query($db->getConnection(),$query2);
if($result2){
while($row2 = mysqli_fetch_array($result2)){
$tmp2 = array();
$tmp2["Cid"] = $row2["Cid"];
$tmp2["CName"] = $row2["CName"];
$tmp2["Content"] = $row2["Content"];
array_push($tmp1["C"], $tmp2);
}
}
array_push($tmp["B"], $tmp1);
}
}
array_push($response["content_info"], $tmp);
}
Set this to echo json_encode($response,true) for an associative array
Related
I have a master query, I am getting data from query and showing in JSON form. Now master query has multiple rows in second table which are child rows with foreign key. My master query data showing right JSON with object but I can not merge both with one index
{
"0": [
{
"FILE_PATH": "IMG_20190917_11224674.jpg"
},
{
"FILE_PATH": "IMG_20190917_11122730.jpg"
},
{
"FILE_PATH": "20190917_110327.mp4"
},
{
"FILE_PATH": "IMG-20190920-WA0006.jpg"
},
{
"FILE_PATH": "20190917_110322150_cf27153e9a2370154223da9c3490e109.mp4"
}
],
"Result": [
{
"INC_ID": "8",
"INC_NAME": "google map",
"INC_LOCATION": "Plot 55 K, Block K Model Town, Lahore, Punjab, Pakistan",
"INC_CATEGORY": "Near Miss",
"INC_LAT": "31.4842451",
"INC_LONG": "74.3135311",
"INC_DATE": "23-SEP-19 05.36.45.000000 PM",
"UNIT_CODE": "1",
"INC_REMARKS": "nfjfrjxi",
"INC_ACTION": "Pending",
"CREATED_BY": "rashid.hanif#sgroup.pk",
"UPDATE_BY": null,
"LOC_ID": "1",
"INC_DATE_FORM": "23-09-19 05:09:45 PM"
},
{
"INC_ID": "7",
"INC_NAME": "testing for new versuon ",
"INC_LOCATION": "Plot 102K, Block K Model Town, Lahore, Punjab, Pakistan",
"INC_CATEGORY": "Injury",
"INC_LAT": "0",
"INC_LONG": "0",
"INC_DATE": "23-SEP-19 05.34.37.000000 PM",
"UNIT_CODE": "41",
"INC_REMARKS": " this",
"INC_ACTION": "Pending",
"CREATED_BY": "rashid",
"UPDATE_BY": null,
"LOC_ID": "4",
"INC_DATE_FORM": "23-09-19 05:09:37 PM"
},
<?php
include 'connection.php';
$details = array();
$details1 = array();
$UNIT_CODE=$_REQUEST["UNIT_CODE"];
$query=oci_parse($c,"select a.* , TO_CHAR(INC_DATE,'dd-mm-yy hh:mm:ss AM' ) as INC_DATE_FORM from hss_incidents a where a.UNIT_CODE IN ($UNIT_CODE) ORDER BY INC_DATE DESC
");
$response = oci_execute($query);
$B = oci_num_rows($query);
if($B >= 0){
while ($row = oci_fetch_array($query, OCI_ASSOC + OCI_RETURN_NULLS)) {
$details[] = $row;
$ABC=$row['INC_ID'];
$query1=oci_parse($c,"select FILE_PATH
from
hss_incidents a, hss_location b, hss_files c
where a.LOC_ID=B.LOC_ID
AND a.INC_ID='$ABC'
");
$response1 = oci_execute($query1);
while ($row1 = oci_fetch_array($query1, OCI_ASSOC + OCI_RETURN_NULLS)) {
$details1[] = $row1;
}
}
echo json_encode(array("Result"=>$details,$details1));
}
else{
echo "No Data Found";
}
?>
Expected Result:
"Result": [
{
"INC_ID": "8",
"INC_NAME": "google map",
"INC_LOCATION": "Plot 55 K, Block K Model Town, Lahore, Punjab, Pakistan",
"INC_CATEGORY": "Near Miss",
"INC_LAT": "31.4842451",
"INC_LONG": "74.3135311",
"INC_DATE": "23-SEP-19 05.36.45.000000 PM",
"UNIT_CODE": "1",
"INC_REMARKS": "nfjfrjxi",
"INC_ACTION": "Pending",
"CREATED_BY": "rashid.hanif#sgroup.pk",
"UPDATE_BY": null,
"LOC_ID": "1",
"INC_DATE_FORM": "23-09-19 05:09:45 PM"
}, "Images"[ {
"FILE_PATH": "IMG_20190917_11224674.jpg"
},
{
"FILE_PATH": "IMG_20190917_11122730.jpg"
},
{
"FILE_PATH": "20190917_110327.mp4"
}]
]
I currently have the following table set up:
StartTime EndTime Performer Event Day Location
-----------------------------------------------------
1:00pm 2:00pm Test Test 0 1
11:00pm 12:00am Test Test 0 0
2:00pm 2:30pm Test Test 1 0
11:00pm 12:00am Test Test 2 1
The JSON output looks something like this:
{
"day0": {
"item1": {
"StartTime": "1:00pm",
"EndTime": "2:00pm",
"Performer": "Test",
"Event": "Test",
"Location": 1
},
"item2": {
"StartTime": "11:00pm",
"EndTime": "12:00am",
"Performer": "Test",
"Event": "Test",
"Location": 0
}
},
"day1": {
"item1": {
"StartTime": "2:00pm",
"EndTime": "2:30pm",
"Performer": "Test",
"Event": "Test",
"Location": 0
}
},
"day2": {
"item1": {
"StartTime": "11:00pm",
"EndTime": "12:00am",
"Performer": "Test",
"Event": "Test",
"Location": 1
}
}
}
Since I'm still learning PHP, I wrote some sloppy code by making 3 queries to the database, each time selecting all data where the day was 1, 2, and 3.
Here's an example of code for fetching data for day=0, which is repeated for day=1 and day=2:
echo '{ "day0" : {';
$sql = "select * from table WHERE day = 0";
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
$jsonData = array();
$rowCount = $result->num_rows;
$index = 1;
while($row =mysqli_fetch_assoc($result))
{
echo '"item'.$index.'":';
echo json_encode(array("StartTime" => $row['StartTime'], "EndTime" => $row['EndTime'], "Performer" => $row['Performer'], "Event" => $row['Event'], "Location" => intval($row['Location'])));
if ($rowCount != $index)
{
echo ',';
}
++$index;
}
echo ' }';
// Repeated code for day=1
// Repeated code for day=2
echo ' }';
I feel as though this can be achieved with just one query, but being that I'm new, I'm not sure how to implement it.
I started to do something like this:
$sql = "select * from table";
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
$jsonData = array();
$numOfRows = $result->num_rows;
$count = 1;
while($row = mysqli_fetch_assoc($result))
{
$outerIndex = 'day'.$row['day'];
if ($row['day'] == '1')
{
// Do something, not sure
}
if ( !isset( $jsonData[$outerIndex] ) )
{
$innerIndex = 'item'.$count.'';
$jsonData[$outerIndex][$innerIndex] = $row;
}
++$count;
}
echo json_encode($jsonData);
However, I just got stuck, and not really sure how to approach it further.
SQL:
$sql = "SELECT * FROM table ORDER BY Day";
Further down on code:
$result_object = [];
$item = 1;
while ($row = $result->fetch_assoc()) {
if(isset($result_object['day'.$row['Day']]))
{
$result_object['day'.$row['Day']]['item'.$item] = $row;
$item++;
}
else
{
$result_object['day'.$row['Day']]['item1'] = $row;
$item = 2;
}
}
You can then output it with:
echo json_encode($result_object, JSON_PRETTY_PRINT); //JSON_PRETTTY_PRINT is not necessary...
You may disagree with me, but I don't think indexing items with item0, item1 and so on.... or day0, day1 ... is a GOOD idea. I personally prefer that the looping through the result would be:
while ($row = $result->fetch_assoc()) {
if(isset($result_object[$row['Day']]))
{
$result_object[$row['Day']]->items[] = $row;
}
else
{
$result_object[$row['Day']] = (object)['day'=>$row['Day'], 'items'=>[$row]];
}
}
In this case, the result would be an array of objects. ie:
[
{
"day": "0",
"items": [
{
"StartTime": "07:23:56",
"EndTime": "17:24:04",
"Performer": "Performer1",
"Event": "Event1",
"Day": "0",
"Location": "1"
},
{
"StartTime": "09:24:30",
"EndTime": "01:04:37",
"Performer": "Performer2",
"Event": "Event2",
"Day": "0",
"Location": "1"
}
]
},
{
"day": "1",
"items": [
{
"StartTime": "10:25:22",
"EndTime": "11:25:29",
"Performer": "Performer2",
"Event": "Event3",
"Day": "1",
"Location": "2"
}
]
},
{
"day": "2",
"items": [
{
"StartTime": "12:26:08",
"EndTime": "13:26:12",
"Performer": "Performer3",
"Event": "Event4",
"Day": "2",
"Location": "1"
}
]
}
]
The reason: you can easily iterate through each values(an array) in whatever language you're going to use.
I have the following code:
$retarray = array();
$hoursarray = array();
$res = $this->mysqli->query("SELECT id, title, groupby FROM scheduler_activity WHERE gewerbe = '$this->gewerbe'");
while($row = $res->fetch_object()) {
$foo = $this->mysqli->query("SELECT dow, start, end FROM scheduler_businesshours WHERE activity = '$row->id'");
while($hours = $foo->fetch_object()){
$hoursarray[] = $hours;
}
$retarray[] = $row;
$retarray["businessHours"] = $hoursarray;
}
return $retarray;
And the following JSON output:
{
"0": {
"id": "1",
"title": "Spinning",
"groupby": "Trainingsgruppe"
},
"businessHours": [{
"dow": "[1,2,3]",
"start": "17:00:00",
"end": "18:00:00"
}, {
"dow": "[4,5]",
"start": "17:30:00",
"end": "18:30:00"
}],
"1": {
"id": "2",
"title": "Massage",
"groupby": "Trainingsgruppe"
},
"2": {
"id": "3",
"title": "Yoga",
"groupby": "Trainingsgruppe"
},
"3": {
"id": "4",
"title": "Dance Academy",
"groupby": "Trainingsgruppe"
}
}
So far it looks correct but I need to get rid of the leading numbers like 0, 1, 2, 3
That it will look like this plus the businessHours:
[{
"id": "1",
"title": "Spinning",
"groupby": "Trainingsgruppe"
}, {
"id": "2",
"title": "Massage",
"groupby": "Trainingsgruppe"
}, {
"id": "3",
"title": "Yoga",
"groupby": "Trainingsgruppe"
}, {
"id": "4",
"title": "Dance Academy",
"groupby": "Trainingsgruppe"
}]
What did I do wrong there?
Thank you!
As I understood about your code, we get business hour for each activity, so it's just a small change at line 10:
$retarray = array();
$hoursarray = array();
$res = $this->mysqli->query("SELECT id, title, groupby FROM scheduler_activity WHERE gewerbe = '$this->gewerbe'");
while($row = $res->fetch_object()) {
$foo = $this->mysqli->query("SELECT dow, start, end FROM scheduler_businesshours WHERE activity = '$row->id'");
while($hours = $foo->fetch_object()){
$hoursarray[] = $hours;
}
$row["businessHours"] = $hoursarray; // Change to this, swap line 10 & 11
$retarray[] = $row;
}
return $retarray;
Hope this helps.
You add two keys. One key is numeric the second is businessHours.
$retarray[] = $row;
$retarray["businessHours"] = $hoursarray;
For instance you can add it businessHours to $row
$row["businessHours"] = $hoursarray;
$retarray[] = $row;
Have you try array_values($array)?
$retarray = array();
$hoursarray = array();
$res = $this->mysqli->query("SELECT id, title, groupby FROM scheduler_activity WHERE gewerbe = '$this->gewerbe'");
while($row = $res->fetch_object()) {
$foo = $this->mysqli->query("SELECT dow, start, end FROM scheduler_businesshours WHERE activity = '$row->id'");
while($hours = $foo->fetch_object()){
$hoursarray[] = $hours;
}
$retarray[] = $row;
$retarray["businessHours"] = $hoursarray;
}
return array_values($retarray);
I want create a json response with nested json object and group my actual results by id_hotel
MY ACTUAL JSON RESPONSE
{
"tag": "cities",
"success": 1,
"error": 0,
"items": 2,
"item": [
{
"id": "6194",
"year": "2013",
"city": "London",
"start": "1",
"id_hotel": "20001",
"name": "hotel piccadilly",
"address": "road 4",
"number_fr": "7003",
"district": "london city",
"pr": "GB",
"fres": "1",
"mode": "Night",
"pos": "402",
"pes": "33",
"pis": "21",
"pus": "456"
},
{
"id": "6194",
"year": "2013",
"city": "London",
"start": "1",
"id_hotel": "20001",
"name": "hotel piccadilly",
"address": "road 4",
"number_fr": "7003",
"district": "london city",
"pr": "GB",
"fres": "1",
"mode": "Day",
"pos": "0",
"pes": "1",
"pis": "0",
"pus": "1"
}
]
}
MY PHP CODE for the encoding response
$query = "SELECT * FROM cities WHERE city = 'London'";
$result = mysql_query($query) or die(mysql_error());
// check for empty result
if (mysql_num_rows($result) > 0) {
$response["item"] = array();
while ($row = mysql_fetch_array($result)) {
// temp user array
$product = array();
$product["id"] = $row["id"];
$product["year"] = $row["year"];
$product["city"] = $row["city"];
$product["start"] = $row["start"];
$product["id_hotel"] = $row["id_hotel"];
$product["name"] = $row["name"];
$product["address"] = $row["address"];
$product["number_fr"] = $row["number_fr"];
$product["district"] = $row["district"];
$product["pr"] = $row["pr"];
$product["fres"] = $row["fres"];
$product["mode"] = $row["mode"];
$product["pos"] = $row["pos"];
$product["pes"] = $row["pes"];
$product["pis"] = $row["pis"];
$product["pus"] = $row["pus"];
// push single product into final response array
array_push($response["item"], $product);
}
// success
$response["items"] = mysql_num_rows($result);
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
What I desider
{
"tag": "cities",
"success": 1,
"error": 0,
"items": 2,
"item": [
{
"id": "6194",
"year": "2013",
"city": "London",
"start": "1",
"id_hotel": "20001",
"name": "hotel piccadilly",
"address": "road 4",
"number_fr": "7003",
"district": "london city",
"pr": "GB",
"fres": "1",
"mode": [{
"value" : "Night",
"pos": "402",
"pes": "33",
"pis": "21",
"pus": "456"
},
{ "value" : "Day",
"pos": "0",
"pes": "1",
"pis": "0",
"pus": "1"
}]
}
]
}
thanks in advance for your attention!!
Add option JSON_FORCE_OBJECT in function. You can read about it in http://tr2.php.net/manual/en/json.constants.php .
json_encode($response, JSON_FORCE_OBJECT) ;
1st, I suggest you a small change to save you some lines, and thus, i add some code to achieve what you want
$query = "SELECT * FROM cities WHERE city = 'London'";
$result = mysql_query($query) or die(mysql_error());
// check for empty result
if (mysql_num_rows($result) > 0) {
$response["item"] = array();
$current_id = NULL;
while ($row = mysql_fetch_array($result)) {
if ( $row->id_hotel !== $current_id ){
$response["item"][] = $row;
$response["item"]["mode"] = array();
}
$current_item = end($response["item"]);
$current_item["mode"][] = array("value"=>$row->value, "pes"=>$row->pes);
$current_id = $row->id_hotel;
}
// success
$response["items"] = mysql_num_rows($result);
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
Let me know if it works.
Note: Only used 1 variable for mode, for testing purposes, and didnĀ“t unset the variables that I put into mode array, but should be enough to see if the main idea works. Feeling a bit lazy :P
I am new in PHP. I am trying to format JSON. Here's the relevant code:
$query = mysql_query("SELECT *
FROM `micards` m
JOIN user u ON m.`mobile` = u.phone");
while ($row = mysql_fetch_assoc($query)) {
$response["success"] = 1;
$name = array('name'=>$row["name"],'email'=>$row["email"],'mobile'=>$row["mobile"]);
$phone[] = array('phone'=>$row["phone"],array('card'=>$name));
$response["contacts"] = $phone;
}
echo json_encode($response);
I'm getting this output:
{
"success": 1,
"contacts": [{
"phone": "919898989898",
"0": {
"card": {
"name": "abcd",
"email": "vwxy#test.com",
"mobile": "919898989898"
}
}
}, {
"phone": "919898989898",
"0": {
"card": {
"name": "abcd",
"email": "rstp#test.com",
"mobile": "919898989898"
}
}
}, {
"phone": "8686868686",
"0": {
"card": {
"name": "pan",
"email": "pnqr#gmail.com",
"mobile": "8686868686"
}
}
}, {
"phone": "8686868686",
"0": {
"card": {
"name": "monk",
"email": "abcd#gmail.com",
"mobile": "8686868686"
}
}
}]
}
But I want it to be:
{
"success": 1,
"contacts": [{
"phone": "919898989898",
{
"card": {
"name": "abcd",
"email": "vwxy#test.com",
"mobile": "919898989898"
}
},
{
"card": {
"name": "abcd",
"email": "rstp#test.com",
"mobile": "919898989898"
}
}
}],
[{
"phone": "8686868686",
{
"card": {
"name": "panky",
"email": "pnqr#gmail.com",
"mobile": "8686868686"
}
},
{
"card": {
"name": "panky",
"email": "abcd#gmail.com",
"mobile": "8686868686"
}
}
}]
}
What can I do to get the above output?
just change this part:
$phone[] = array('phone'=>$row["phone"],array('card'=>$name));
$response["contacts"] = $phone;
to
$response["contacts"][] = array('phone'=>$row["phone"],array('card'=>$name));
Just copy and paste this code
while ($row = mysql_fetch_assoc($query)) {
$response["success"] = 1;
$name = array('name'=>$row["name"],'email'=>$row["email"],'mobile'=>$row["mobile"]);
$response["contacts"][] = array('phone'=>$row["phone"],array('card'=>$name));
}
Please change
$phone[] = array('phone'=>$row["phone"],array('card'=>$name)) to
$phone[] = array('phone'=>$row["phone"],'card'=>$name)
;
My guess is that there is a problem with associative arrays and the way you are packing it. You can try to organize your response array like this:
$response = [
'success'=>1,
'contacts'=>[
'phone'=>$row['phone'],
'card'=>[
'name'=>$row['name'],
'email'=>$row['email'],
'mobile'=>$row['mobile']
]
]
];
It should work, didn't check it out thou.