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", ...]
...
Related
This is the return result of my two variables:
$resultPayment = [
[72875500, 8187000],
[14343],
[44419200,
["12332000"],
[28700250]
]
$resultId = [
["461", "462"],
[6462],
[8771],
[8461],
[5461]
]
This is the code for get the data:
for ($iii=0; $iii<count($dataInvoice); $iii++) {
$resultId[] = unserialize($dataInvoice[$iii]->invoiceid);
$resultPayment[] = unserialize($dataInvoice[$iii]->jumlahbayarid);
}
These two pieces of data are the same length and array structure, and I want to combine $id and $payment and create an object. Here are the results I expect :
[
{ "461": 72875500 },
{ "462": 8187000 },
{ 6462: 14343 },
{ 8771: 44419200 },
{ 8461: "12332000" },
{ 5461: 28700250 }
]
One possible approach is the following example:
<?php
$payment = [
[72875500, 8187000],
[14343],
[44419200],
["12332000"],
[28700250]
];
$id = [
["461", "462"],
[6462],
[8771],
[8461],
[5461]
];
$payment = call_user_func_array('array_merge', $payment);
$id = call_user_func_array('array_merge', $id);
$result = json_encode(array(array_combine($id, $payment)));
echo $result;
?>
Result:
[{"461":72875500,"462":8187000,"6462":14343,"8771":44419200,"8461":"12332000","5461":28700250}]
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.
(First a bit/lot of context at the bottom is the question)
I am writing an API that returns a planning amongst other things. The response is in JSON and should be as followed:
"Planning":
[
{
"Name": "Overview",
"Dates":
[
{
"Date": "yyyy-mm-dd",
"Division1": "type",
"Division2": "type"
},
{
"Date": "yyyy-mm-dd",
"Division1": "type",
"Division2": "type"
},
...
]
},
{
"Name": "Division1",
"Dates":
[
{
"Date": "yyyy-mm-dd",
"Type": "type",
"Description": "type"
},
...
]
},
...
There is the standard blok "Name": "Overview" this is always returned, and for each division the requester is a part of, a block with "Name":"Divisionname" is added to the response.
The issue I have is that the amount or names of the divisions aren't set in stone. There can be more or less depending on the deployment.
To cover for this I wrote the following code:
<?php
...
$stmt = $conn->prepare("SELECT `idDivision` FROM Division;");
$stmt->execute();
$stmt->bind_result($idDivision);
while($stmt->fetch()){
$Divisions[] = $idDivision;
$$idDivision = array();
}
...
?>
This should create an array for each division with the array name being the id of that division (correct?).
Then I get the planning data from the DB which i store in the multiple arrays that I will later use for the response building:
<?php
$stmt->bind_result($type, $date, $idDivision, $day, $description, $note);
while($stmt->fetch()){
if(checkarray($date, $arr_date) != true){
array_push($arr_date, $date);
array_push($arr_day, $day);
}
array_push($$idDivision, $type); //This should push it into the correct array.
}
?>
At the end I want to combine all this into the respons ofcourse (This is where I am lost):
<?php
for($i = 0; $i <= count($arr_date); $i++){
$planning[0]['Dates'][] = array(
"Date" => $arr_date[$i],
// How to add every division with "arrayname" => "$type" here?
);
}
?>
As in the comment above, i don't know how to add a key:value for each division that i found dynamically so that it becomes:
<?php
for($i = 0; $i <= count($arr_date); $i++){
$planning[0]['Dates'][] = array(
"Date" => $arr_date[$i],
"Division1" => $value,
"Division2" => $value,
"Division3" => $value,
// and so on for every division
);
}
?>
Is there a way to do this or should I even go about doing this a different way? I feel like I should/could use the $Divisions array.
Try out this.
for($i = 0; $i <= count($arr_date); $i++){
$planning[0]['Dates'][$i]["Date"] = $arr_date[$i];
for($j=0;$j<count($division);$j++){
$planning[0]['Dates'][$i]["division$j"] = $division[$j];
}
}
?>
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);
I'm facing an issue regarding the json structure.
I have this:
function loadActiveTrackers($host_l, $username_l, $password_l, $dbName_l, $companyId_l){
$trackerId = 0;
$trackerName = "";
$trackerCreator = "";
$projectName = "";
$dataArray = [];
$trackerIdsArray = [];
$trackerNamesArray = [];
$trackerCreatorsArray = [];
$projectNamesArray = [];
$mysqli = new mysqli($host_l, $username_l, $password_l, $dbName_l);
$getActiveTrackersQuery = "SELECT tracker_id, tracker_name, tracker_creator, project_name FROM trackers WHERE "
. "company_id = ? AND is_active=1 ORDER BY tracker_creation_date";
if($stmt = $mysqli->prepare($getActiveTrackersQuery)){
$stmt->bind_param('s',$companyId_l);
$stmt->execute();
/* Store the result (to get properties) */
$stmt->store_result();
/* Bind the result to variables */
$stmt->bind_result($trackerId, $trackerName, $trackerCreator, $projectName);
while ($stmt->fetch()) {
$trackerIdsArray[] = $trackerId;
$trackerNamesArray[] = $trackerName;
$trackerCreatorsArray[] = $trackerCreator;
$projectNamesArray[] = $projectName;
}
$dataArray['ids'] = $trackerIdsArray;
$dataArray['names'] = $trackerNamesArray;
$dataArray['creators'] = $trackerCreatorsArray;
$dataArray['projectNames'] = $projectNamesArray;
// print_r($trackerIdsArray);
/* free results */
$stmt->free_result();
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
echo json_encode($dataArray);
}
The above code works ok, but the structure is not valid.
What I mean is that it returns:
{
"ids": [1,2,3,4],
"names": ["1","2","test tracker","test1"],
"creators": ["1","test","test","test"],
"projectNames": ["1","1","test project","test"]
}
But it is supposed to return:
[
{"id": 1, "name": "1", "creator": "1", "projectName": "1"},
{"id": 2, "name": "2", "creator": "test", "projectName": "1"},
{"id": 3, "name": "test tracker", "creator": "test", "projectName": "test project"},
{"id": 4, "name": "test1", "creator": "test", "projectName": "test"}
]
Can you guide me trough it? I know that it's something really small, but I'm not able to spot it as a php newbie. In java the json library is pretty strong and with a single push() it can be achieved, but here I really can't find the way.
The current code creates arrays of the ids, names, creators, and project names.
So, instead of this code:
while ($stmt->fetch()) {
$trackerIdsArray[] = $trackerId;
$trackerNamesArray[] = $trackerName;
$trackerCreatorsArray[] = $trackerCreator;
$projectNamesArray[] = $projectName;
}
$dataArray['ids'] = $trackerIdsArray;
$dataArray['names'] = $trackerNamesArray;
$dataArray['creators'] = $trackerCreatorsArray;
$dataArray['projectNames'] = $projectNamesArray;
Change your structure to be like so:
while ($stmt->fetch()) {
$dataArray[] = array( 'id' => $trackerId,
'name' => $trackerName,
'creator' => $trackerCreator,
'projectName' => $projectName
);
}
echo json_encode($dataArray);
This will return the structure you desire, which is arrays of the ids, names, creators, and project names.