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}]
Related
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.
Confusing my values so messy
Home Code
$user = getventList();
$response = array();
if(mysql_num_rows($user) > 0){
while ($row = mysql_fetch_assoc($user)){
$response[] = $row;
echo json_encode($response);
}
} else {
return false;
}
enter code here
Function event
this one is function to generate result from mysql
$result = mysql_query("SELECT * from event where status = '2'");
return $result;
Bad Result
[ {"cPID":"123","image_event":"enjoy.jpg"}
]
[ {"cPID":"123","image_event":"enjoy.jpg"},
{"cPID":"1234","image_event":"enjoy.jpg"}
]
[ {"cPID":"123","image_event":"enjoy.jpg"},
{"cPID":"1234","image_event":"enjoy.jpg"},
{"cPID":"12345","image_event":"enjoy.jpg"}
]
[ {"cPID":"123","image_event":"enjoy.jpg"},
{"cPID":"1234","image_event":"enjoy.jpg"},
{"cPID":"12345","image_event":"enjoy.jpg"},
{"cPID":"123456","image_event":"enjoy.jpg"}
]
[ {"cPID":"123","image_event":"enjoy.jpg"},
{"cPID":"1234","image_event":"enjoy.jpg"},
{"cPID":"12345","image_event":"enjoy.jpg"},
{"cPID":"123456","image_event":"enjoy.jpg"},
{"cPID":"1234567","image_event":"enjoy.jpg"}
]
i wanna get only like the last array
[ {"cPID":"123","image_event":"enjoy.jpg"},
{"cPID":"1234","image_event":"enjoy.jpg"},
{"cPID":"12345","image_event":"enjoy.jpg"},
{"cPID":"123456","image_event":"enjoy.jpg"},
{"cPID":"1234567","image_event":"enjoy.jpg"}
]
Move json_encode out of the while loop. Additionally quit using mysql and start using mysqli or PDO functions.
$user = getventList();
$response = array();
if(mysql_num_rows($user) > 0){
while ($row = mysql_fetch_assoc($user)){
$response[] = $row;
}
} else {
return false;
}
echo json_encode($response);
Now your output will be the expected one
[ {"cPID":"123","image_event":"enjoy.jpg"},
{"cPID":"1234","image_event":"enjoy.jpg"},
{"cPID":"12345","image_event":"enjoy.jpg"},
{"cPID":"123456","image_event":"enjoy.jpg"},
{"cPID":"1234567","image_event":"enjoy.jpg"}
]
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", ...]
...