I have 2 table users(id,userid,fn,ln) and userdetails(id,userid,image,history,location,activity)
And i have written a query for first table to retrieve all the data and i want only history and location ,from second table.
i have retrieved the array and i am sending it to json_encode.
Now i want to retrieve the history,location and create a new key History and i want to add history location values to history key.
I need a query and json format for these.
For particular user i need to retrieve is own history
In both tables user id in common
Thanks in advance
$sth = mysql_query("SELECT * FROM users");$result = mysql_fetch_assoc($sth);
$i=0;
foreach($result as $data) {
$final_array[$i]['id'] = $data['id'];
$final_array[$i]['email'] = $data['email'];
$final_array[$i]['fname'] = $data['fname'];
$final_array[$i]['lname'] = $data['lname'];
$sth2 = mysql_query("SELECT id,places,act FROM user_dates WHERE user_id= '".$data['email']."'");
$result2 = mysql_fetch_assoc($sth2);
$j=0;
$history_array = array();
foreach($result2 as $data2) {
$history_array[$j] = array("id" => $data2['id'],"places" => $data2['places'], "act " => $data2['act ']);
$j++;
}
$final_array[$i]['history'] = $history_array;
$i++;
}
echo json_encode($final_array);
[
{
"id": "81",
"user_id": "2011",
"fn": "asd.",
"ln": "wer",
"History": [
{
"id": "350",
"history": "make1",
"Location": "qwe"
}
]
},
{
"id": "82",
"user_id": "2012",
"fn": "asd1",
"ln": "wer1",
"History": [
{
"id": "350",
"history": "make2",
"Location": "qwe2"
}
]
}
]
Userdetails table contains multiple records per user. So you need to do sub query and get the results and then form a mulch-dimensional array. Finally, encode as a JSON.
$sth = $dbh->prepare("SELECT * FROM users");
$sth->execute();
$result = $sth->fetchAll();
$i=0;
foreach($result as $data) {
$final_array[$i]['id'] = $data['id'];
$final_array[$i]['userid'] = $data['userid'];
$final_array[$i]['fn'] = $data['fn'];
$final_array[$i]['ln'] = $data['ln'];
$sth2 = $dbh->prepare("SELECT location,activity FROM userdetails WHERE userid= ".$data['id']."");
$sth2->execute();
$result2 = $sth2->fetchAll();
$j=0;
$history_array = array();
foreach($result2 as $data2) {
$history_array[$j] = array("location" => $data2['location'], "activity " => $data2['activity ']);
$j++;
}
$final_array[$i]['history'] = $history_array;
$i++;
}
echo json_encode($final_array);
Related
I'm trying to create an array of objects with data coming from multiple tables, lets say there is table that hold patient data and there is table that hold diagnosis, and medicine for every patient that admitted to clinic, and i need to create an array of objects with the following output.
Screen shot
And i have to write the following code
<?php
// Db configs.
define('HOST', 'localhost');
define('PORT', 3306);
define('DATABASE', 'new_nhif');
define('USERNAME', 'root');
define('PASSWORD', '');
error_reporting(E_ALL);
ini_set('display_errors', 1);
$mysqliDriver = new mysqli_driver();
$mysqliDriver->report_mode = (MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$connection = new mysqli(HOST, USERNAME, PASSWORD, DATABASE, PORT);
$sql = sprintf(
'SELECT
nh.MembershipNo,
nh.FullName,
nh.id as nhid,
lb.labrequest,
fd.diagnosis,
fd.DiseaseCode,
fd.CreatedBy as fdcrb,
dz.name
FROM nhif_data AS nh
LEFT JOIN laboratory AS lb ON lb.re_id = nh.id
LEFT JOIN foliodisease AS fd ON fd.re_id = nh.id
LEFT JOIN dawa_zilizotoka AS dz ON dz.re_id = nh.id
WHERE lb.re_id = nh.id
AND fd.re_id = nh.id
AND dz.re_id = nh.id
-- GROUP BY nh.MembershipNo
'
);
$obj = new stdClass;
$result = $connection->query($sql);
$vipimo = array();
$dawa = array();
$all = array();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
// print_r(json_encode(['entities'=> $row],JSON_PRETTY_PRINT));
$obj->MembershipNo = $row['MembershipNo'];
$obj->FullName = $row['FullName'];
$id = $row['nhid'];
$sql2 = "SELECT * FROM foliodisease WHERE re_id ='$id'";
$result1 = $connection->query($sql2);
if ($result1->num_rows > 0) {
while($row2 = $result1->fetch_assoc()) {
$vipimo['diagnosis']= $row2['diagnosis'];
$vipimo['DiseaseCode']= $row2['DiseaseCode'];
$obj->FolioDiseases[] = $vipimo;
}
}
$sql3 = "SELECT * FROM dawa_zilizotoka WHERE re_id = $id";
$result3 = $connection->query($sql3);
if ($result3->num_rows > 0) {
while($row3 = $result3->fetch_assoc()) {
$dawa['name']= $row3['name'];
$obj->FolioItems[] = $dawa;
}
}
$all[] = $obj;
}
print_r(json_encode(['entities'=> $all], JSON_PRETTY_PRINT));
}
?>
And it give out the following output
{
"entities": [
{
"MembershipNo": "602124502",
"FullName": "Omari M Simba",
"FolioDiseases": [
{
"diagnosis": "typhoid",
"DiseaseCode": "J54"
},
{
"diagnosis": "homa",
"DiseaseCode": "L54"
},
{
"diagnosis": "malaria",
"DiseaseCode": "b54"
}
],
"FolioItems": [
{
"name": " Fluticasone furoate\t"
},
{
"name": " Acyclovir Eye ointment\t"
},
{
"name": " Acyclovir\t"
},
{
"name": " Acyclovir\t"
}
]
},
{
"MembershipNo": "602124502",
"FullName": "Omari M Simba",
"FolioDiseases": [
{
"diagnosis": "typhoid",
"DiseaseCode": "J54"
},
{
"diagnosis": "homa",
"DiseaseCode": "L54"
},
{
"diagnosis": "malaria",
"DiseaseCode": "b54"
}
],
"FolioItems": [
{
"name": " Fluticasone furoate\t"
},
{
"name": " Acyclovir Eye ointment\t"
},
{
"name": " Acyclovir\t"
},
{
"name": " Acyclovir\t"
}
]
}
]
}
My tables are
nhif_data ----
nhif_data ,
laboratory ----
laboratory,
foliodisease ---
foliodisease ,
dawa_zilizotoka ----
dawa_zilizotoka
You don't need to create an object array for the desired output, 'json_encode()' basically objectifies anything, meaning, no matter what you store with 'json_encode()' function, 'json_decode()' will always return you an object/array of objects, and so on.
All you need to fetch the records off the database, make child nesting as required, append the record to an array, and just 'json_encode()'; with 'json_decode()', you will end up with an array of objects.
$JSONItem = []; // Initialize the array
while($Record = $Query->fetch_assoc()){ // Iterate through main recordset
...subsequent child query
// Iterate though child recordset
while($ChildRecord = $ChildQuery->fetch_assoc())$Record["Child"][] = $ChildRecord; // Append child node to main record
$JSONItem[] = $Record; // Append record for JSON conversion
}
var_dump(json_decode(json_encode($JSONItem))); // This should return an array of ojects
Following should allow a better understanding of the mechanism;
var_dump(json_decode(json_encode([
["ID" => 1, "Name" => "Apple", "Source" => ["Name" => "Amazon", "URL" => "http://Amazon.Com", ], ],
["ID" => 2, "Name" => "Banana", "Source" => ["Name" => "eBay", "URL" => "http://eBay.Com", ], ],
["ID" => 3, "Name" => "Carrot", "Source" => ["Name" => "GearBest", "URL" => "http://GearBest.Com", ], ],
])));
Or, with newer PHP version, I hope you can simply prepare/construct the array and objectify it with something like;
$JSON = (object) $JSONItem;
I have this data but I can't parse it in the way I want. this is what I get:
{
"navigations": {
"title": "Facebook",
"link": "https://facebook.com",
"behavior": "EXTERNAL"
}
}
And what I expect to see:
{
"navigations": [
{
"title": "Facebook",
"url": "https://facebook.com",
"behavior": "INAPP"
},
{
"title": "Youtube",
"url": "https//youtube.com",
"behavior": "INAPP"
}
]
}
I have more results in my database but not more than 12 result so, i want to fetch data in the format i expect. I tried to do it using fetch_array but no success.
This is my PHP code:
$query_update_navigations = $db->prepare("SELECT title, link, behavior FROM navigation_tabs WHERE secret_api_key=?");
$query_update_navigations->bind_param("s", $_SESSION['secret_api_key']);
$query_update_navigations->execute();
$rows = array();
$result = $query_update_navigations->get_result();
while($rows1 = $result->fetch_assoc()) {
$rows['navigations'] = $rows1;
}
$store_path = '../apis/navigation_tabs/';
$file_name = $_SESSION['secret_api_key'] . '.json';
$sign_constants = json_encode($rows);
file_put_contents($store_path . $file_name, $sign_constants);
I searched for an answer but nothing solved my issue :(
You need to push the row onto the array, not overwrite it each time.
$rows = array('navigations' => []);
$result = $query_update_navigations->get_result();
while($rows1 = $result->fetch_assoc()) {
$rows['navigations'][] = $rows1;
}
My database have three tables(category,catgory_details,questions), Now one category have many questions. I want to have a JSON response like this:
[
{
"category": "Accountant",
"deatils": {
"video_link": "https://www.youtube.com/",
"form_link": "https://docs.google.com/forms/u/0/",
"questions": [
"Who is your idiol",
"What is ur name?"
]
}
},
{
"category": "Actuary",
"deatils": {
"video_link": "https://www.youtube.com/",
"form_link": "https://docs.google.com/forms/u/0/",
"questions": [
"What is great?",
"What is ur name?"
]
}
}
]
but my code is returning only one row from questions tables like this:
[
{
"category": "Accountant",
"deatils": {
"video_link": "https://www.youtube.com/",
"form_link": "https://docs.google.com/forms/u/0/",
"questions": [
"Who is your idiol"
]
}
},
{
"category": "Actuary",
"deatils": {
"video_link": "https://www.youtube.com/",
"form_link": "https://docs.google.com/forms/u/0/",
"questions": [
"What is great?"
]
}
}
]
Following is my php code:
<?php
header("Content-Type: application/json");
include('db.php');
$result = mysqli_query($conn,"SELECT * FROM categories ORDER BY id ASC");
$json_response = array();
while ($row = mysqli_fetch_array($result))
{
$row_array = array();
$row_array['category'] = $row['category'];
$id = $row['id'];
$detail_query = mysqli_query($conn,"SELECT * FROM category_details WHERE category_id=$id");
$question_query = mysqli_query($conn,"SELECT * FROM questions WHERE category_id=$id");
if($question_query->num_rows !== 0){
while ($detail_fetch = mysqli_fetch_array($detail_query))
{
while ($question_fetch = mysqli_fetch_array($question_query))
{
$row_array['deatils'] = array(
'video_link' => $detail_fetch['video_link'],
'form_link' => $detail_fetch['form_link'],
'questions' => [$question_fetch['question'][1],$question_fetch['question'][2]],
);
}
}
}
else{
while ($detail_fetch = mysqli_fetch_array($detail_query))
{
$myid = $detail_fetch['id'];
$row_array['deatils'] = array(
'video_link' => $detail_fetch['video_link'],
'form_link' => $detail_fetch['form_link'],
);
}
}
array_push($json_response, $row_array);
}
echo json_encode($json_response);
?>
What changes should I make in order to get my required JSON response?
Instead of building $row_array['deatils'] within the question_fetch loop, you should do it within the detail_fetch loop, and then populate just the questions sub-array within the question_fetch loop
while ($detail_fetch = mysqli_fetch_array($detail_query))
{
$row_array['deatils'] = array(
'video_link' => $detail_fetch['video_link'],
'form_link' => $detail_fetch['form_link'],
'questions' => array(),
);
while ($question_fetch = mysqli_fetch_array($question_query))
{
$row_array['deatils']['questions'][] = $question_fetch['question'];
}
}
Try to change :
'questions' => [$question_fetch['question'][1],$question_fetch['question'][2]],
to :
'questions' => $question_fetch['question'],
So you will have the full array of questions included in the response.
I have a mysql table (name:"messages") that has three columns as below:
messageID, fromUserID, content
I wish to have a json output using php script like following format; I need to seprate messages of each user (fromUserID column).
JSONOutput:
{
"newCount":"x",
"messages":
[
{
"fromUserID":"x",
"messagesArray":
[
{"messageID":"x","content":"xxx"},
{"messageID":"x","content":"xxx"},
{"messageID":"x","content":"xxx"}
]
},
{
"fromUserID":"y",
"messagesArray":
[
{"messageID":"x","content":"xxx"},
{"messageID":"x","content":"xxx"},
{"messageID":"x","content":"xxx"}
]
},
{
"fromUserID":"z",
"messagesArray":
[
{"messageID":"x","content":"xxx"},
{"messageID":"x","content":"xxx"},
{"messageID":"x","content":"xxx"}
]
}
]
}
My PHP Script:
$query = mysqli_query($con,"SELECT * FROM messages ORDER BY fromUserID");
$outputArray = array();
$outputArray['hasNew'] = mysqli_num_rows($query);
$messagesArray = array();
if($query)
{
while($row = mysqli_fetch_assoc($query))
{
$MSGArray = array();
$messagesArray['fromUserID'] = $row['fromUserID'];
$MSGArray['messageID'] = $row['messageID'];
$MSGArray['content'] = $row['content'];
$messagesArray['MessagesArray'][] = $MSGArray;
}
$outputArray['Messages'][] = $messagesArray;
}
echo json_encode($outputArray);
But with above script I give a wrong result as below:
{
"hasNew":6,
"Messages":
[
{
"fromUserID":"24",
"MessagesArray":
[
{"messageID":"4","content":"test"},
{"messageID":"3","content":"test"},
{"messageID":"6","content":"test"},
{"messageID":"5","content":"test"},
{"messageID":"1","content":"test"},
{"messageID":"2","content":"test"}
]
}
]
}
My PHP Script just using last fromUserID value to grouping messages !!!
Please let me know where I'm wrong ...
Try it
if($query)
{
while($row = mysqli_fetch_assoc($query))
{
$MSGArray = array();
$messagesArray[$row['fromUserID']]['fromUserID'] = $row['fromUserID'];
$MSGArray['messageID'] = $row['messageID'];
$MSGArray['content'] = $row['content'];
$messagesArray[$row['fromUserID']]['MessagesArray'][] = $MSGArray;
}
foreach($messagesArray as $value) {
$outputArray['Messages'][] = $value;
}
}
I have a class property where i define an associative array
private $jsonArray = array('Friends' => array());
Im trying to have the array have each friend be put into the array Friends
[Accepted] = test
$query = "SELECT Username, Status
FROM Users
INNER JOIN Friends
ON Users.idUser = Friends.idFriend
WHERE Friends.idUser = ? ";
// Prepares and excutes the query
if($stmt = $this->connection->prepare($query))
{
$stmt->bind_param('s', $this->id);
$stmt->execute();
$stmt->bind_result($friend, $status);
for ($i=0; $stmt->fetch(); $i++)
{
$this->jsonArray['Friends'][$status] = $friend;
}
}
Is this the correct way to define the key for the friend it works but when i json encode its a dict and no longer an array
{
"response": {
"status":"Success",
"friends": [
"Andrew",
"Jake",
"Matt",
"Phil",
"Colton"
],
"groups": [
{
"GroupId": "12",
"GroupMembers": [
"Andrew",
"Matt",
"Colton"
],
"GroupName": “Group1”
},
{
"GroupId": "12",
"GroupMembers": [
"Phil",
"Matt",
"Colton"
],
"GroupName": "Room 201"
}
]
}
}
With this you'll always have one $friend per [$status] - if that is wanted, then it's ok. But from the looks, you'd be better off with something like this
for ($i=0; $stmt->fetch(); $i++) {
$this->jsonArray['Friends'][$status][] = $friend;
}
Now you'll have an array of $friends inside [$status].
...
Friends: {
"Accepted": ["friend1", "friend2", ...]
}
...
Or this
for ($i=0; $stmt->fetch(); $i++) {
$this->jsonArray['Friends'][] = $friend;
}
Since you know their $status - why even use it?
...
Friends: ["friend1", "friend2", ...]
...