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;
}
}
Related
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;
}
I amnot familiar php arrays. Therefore I couldn't solve that problem :
My data comes from database. I didn't post database connection parts, they work perfectly. As I understand I need to use multidimensional array. My Json format should be like this
{
"monthly":[
{
"id":1,
"name":"This is a JSON event",
"startdate":"2016-9-15",
"enddate":"2016-9-15",
"starttime":"12:00",
"endtime":"2:00",
"color":"#FFB128",
"url":""
},
{
"id":2,
"name":"This is a JSON event",
"startdate":"2019-3-25",
"enddate":"2019-3-25",
"starttime":"12:00",
"endtime":"23:00",
"color":"#EF44EF",
"url":""
}
]
}
My PHP script (relevant part) :
try {
$q = "SELECT * FROM eventcalendar";
$res = $db->prepare($q);
$res->execute();
if ($res->rowCount() != 0) {
$data = array('monthly' => array());
$push_array = array();
foreach ($res as $key) {
$data['monthly']['id'] = $key['id'];
$data['monthly']['name'] = $key['name'];
$data['monthly']['startdate'] = $key['startdate'];
$data['monthly']['enddate'] = $key['startdate'];
$data['monthly']['color'] = $key['color'];
$data['monthly']['starttime'] = 12;
$data['monthly']['endtime'] = 12;
$data['monthly']['url'] = "";
array_push($push_array, $data);
}
file_put_contents('../js/events.json', json_encode($push_array));
echo('<div class="alert alert-success resultsuccess" ><h4 class="alert-heading">Successful!</h4></div>');
}
} catch (Exception $e) {
echo('<div class="alert alert-danger resultsuccess" >'.'Error: '.$e->getMessage().'</div>');
}
I get that JSON format
[
{
"monthly":{
"id":"1",
"name":"test1",
"startdate":"2019-03-29",
"enddate":"2019-03-29",
"color":"#ffb128",
"starttime":12,
"endtime":12,
"url":""
}
},
{
"monthly":{
"id":"2",
"name":"test2",
"startdate":"2019-03-29",
"enddate":"2019-03-29",
"color":"#4263e6",
"starttime":12,
"endtime":12,
"url":""
}
}
]
Thanks for reading...
Your problem is that you are creating new arrays with a monthly index on each pass through your loop, instead of pushing the new data into the existing monthly array. Try this instead:
if ($res->rowCount() != 0) {
$push_array = array('monthly' => array());
$data = array();
foreach ($res as $key) {
$data['id'] = $key['id'];
$data['name'] = $key['name'];
$data['startdate'] = $key['startdate'];
$data['enddate'] = $key['startdate'];
$data['color'] = $key['color'];
$data['starttime'] = 12;
$data['endtime'] = 12;
$data['url'] = '';
array_push($push_array['monthly'], $data);
}
I am trying to build a JSON response from my server side, but it is not working as expected.
It is probably something simple but, I am not so good at PHP...
The basic expected response is a JSON with a single JsonArray and some other fields, for that, the relevant piece of code is shown here:
Sample of expected JSON response:
{
"pageNr": 2
"totalPages":28
"products":[
{
"user_name":"testUser001",
"product_ID":"4756373abdhg"
},
{
"user_name":"testUser002",
"product_ID":"475ggdfghghg"
},
{
"user_name":"testUser003",
"product_ID":"47466gdgbdhg"
},
{
"user_name":"testUser004",
"product_ID":"4000nfaergeb"
},
{
"user_name":"testUser005",
"product_ID":"adfer73abdhg"
}
]
}
Basic PHP code used to generate desired JSON (among sql query and other things):
$res = array();
$res2 = array();
while($r = mysqli_fetch_assoc($query2)) {
$res["user_name"] = $r["user_name"];
$res["product_ID"] = $r["prod_ID"];
array_push($res2,$res);
}
$response = ['pageNr' => $page];
$response = ['totalPages' => $totalPages];
$response = ['products' => $res2];
Response that this code is generating on Postman:
{
"products":[
{
"user_name":"testUser001",
"product_ID":"4756373abdhg"
},
{
"user_name":"testUser002",
"product_ID":"475ggdfghghg"
},
{
"user_name":"testUser003",
"product_ID":"47466gdgbdhg"
},
{
"user_name":"testUser004",
"product_ID":"4000nfaergeb"
},
{
"user_name":"testUser005",
"product_ID":"adfer73abdhg"
}
]
}
So, for some reason the JSON response is not accepting more fields pageNrand totalPages.
What is wrong here?.
Each assignment overwrites your array. You need to update it instead:
$res = array();
$res2 = array();
while($r = mysqli_fetch_assoc($query2)) {
$res["user_name"] = $r["user_name"];
$res["product_ID"] = $r["prod_ID"];
array_push($res2,$res);
}
$response = [];
$response['pageNr'] = $page;
$response['totalPages'] = $totalPages;
$response['products'] = $res2;
Try;
$res = array();
$res2 = array();
while($r = mysqli_fetch_assoc($query2)) {
$res["user_name"] = $r["user_name"];
$res["product_ID"] = $r["prod_ID"];
array_push($res2,$res);
}
$response .= ['pageNr' => $page];
$response .= ['totalPages' => $totalPages];
$response .= ['products' => $res2];
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.
This is almost exactly what I want, but that question hasn't been answered and it's been a year. I've managed to get close, I think, but numbers are being printed as keys. In my example it shows up on line 47, but it is repeated for every "course_name" in the actual file.
[
{
"school_name": "Projects",
"terms": [
{
"term_name":"category_name#1",
"departments": [
{
"department_name":"sub_category_name1",
"department_code":"category code text here",
"courses":[
{
"course_name": "project1",
"course_code":"project 1 code text goes here",
"sections":[
{
"section_code":"mike",
"unique_id":"xxx#mail.com"
},
{
"section_code":"dan",
"unique_id":"xxx#gmail.com"
}
]
},
{
"course_name": "project2",
"course_code":"project 2 code text goes here",
"sections":[
{
"section_code":"steve",
"unique_id":"xxx#mail.com"
},
{
"section_code":"chris",
"unique_id":"xxx#gmail.com"
}
]
}
]
},
{
"department_name": "sub_category_name2",
"department_code":"sub category description text goes here..",
"courses": {
-->>> "69": {
"course_name": "project3",
"course_code":"project3 code text goes here ",
"sections":[
{
"section_code":"Alex",
"unique_id":"xxx#gmail.com"
}
]
}
}
}
]
}
]
}
]
Here is the query I am using and an example of data being returned.
SELECT school_name, term_name, department_name, department_code, course_code, course_name, section_code, magento_course_id
FROM schools INNER JOIN term_names ON schools.id=term_names.school_id INNER JOIN departments ON schools.id=departments.school_id INNER JOIN
adoptions ON departments.id=adoptions.department_id
"UCA-2" "SPRING 2013" "ACCOUNTING" "ACCT" "3315" "COST ACCOUNTING" "10258" 10311
What I have is being generated with this code.
$row_array = array();
$terms = array();
$departments = array();
$courses = array();
$h = 0;
$i = 0;
$j = 0;
while ($row = mysqli_fetch_assoc($fetch)) {
$row_array[$row['school_name']]['school_name'] = $row['school_name'];
$akey = array_search($row['term_name'], $terms);
if ($akey === FALSE) {
$m = $h++;
$terms[] = $row['term_name'];
$row_array[$row['school_name']]['terms'][$m]['term_name'] = $row['term_name'];
} else {
$m = $akey;
}
$key = array_search($row['department_code'], $departments);
if ($key === FALSE) {
$k = $i++;
$departments[] = $row['department_code'];
$row_array[$row['school_name']]['terms'][$m]['departments'][$k]['department_name'] = $row['department_name'];
$row_array[$row['school_name']]['terms'][$m]['departments'][$k]['department_code'] = $row['department_code'];
} else {
$k = $key;
}
$skey = array_search($row['course_code'], $courses);
if ($skey === FALSE) {
$l = $j++;
$courses[] = $row['course_code'];
$row_array[$row['school_name']]['terms'][$m]['departments'][$k]['courses'][$l]['course_name'] = $row['course_name'];
$row_array[$row['school_name']]['terms'][$m]['departments'][$k]['courses'][$l]['course_code'] = $row['course_code'];
} else {
$l = $skey;
}
$row_array[$row['school_name']]['terms'][$m]['departments'][$k]['courses'][$l]['sections'][] = array('section_code' => $row['section_code'], 'unique_id' => $row['magento_course_id']);
}
How do I generate this JSON without those numbers showing up?
I think you have some key & encoding problems. Too much key usage, excessive loops in your code. Maybe you should tidy your sql query.
Since you are setting keys for courses, JSON shows it.
Try removing the key after "['courses']" in your last line such as;
Change ['courses'][$l] to ['courses'][]
At the end, encode the array for JSON.
$result = json_encode($result);