I'm writing a PHP code for inserting the work order name in a spinner.
I need a JSON String called success = 1 along with JSON Array.
I want to use that JSON string in the android spinner.
I'm getting only JSON array.
here is my code:
<?PHP
require_once('connection.php');
$workName = "SELECT workorder_name FROM workorder_category";
$con=mysqli_connect($server_name,$user_name,$password,$db);
$r = mysqli_query($con,$workName);
$result = array();
$resultArr = array('success' => true);
while($row = mysqli_fetch_array($r)){
array_push($result,array('$workOrderName'=>$row['workorder_name']));
}
echo json_encode(array('result'=>$result));
mysqli_close($con);
?>
I want an output as like this:
{"success":1,result":[{"$workOrderName":"electrician"},{"$workOrderName":"plumber"},{"$workOrderName":"carpenter"}]}
currently, I am getting the output like
{
"result": [
{
"$workOrderName": "electrician"
},
{
"$workOrderName": "plumber"
},
{
"$workOrderName": "carpenter"
}
]
}
Instead of creating two arrays, one for the result and one for the success, define the structure in just one array and append to that:
// The main structure
$result = [
'success' => 1,
'result' => [],
];
while($row = mysqli_fetch_array($r)){
// Append to the sub key "result" (which we already defined as an array)
$result['result'][] = ['$workOrderName'=>$row['workorder_name']];
}
// Just encode the complete array
echo json_encode($result);
Note: This example uses the short array syntax [] (introduced in PHP 5.4) instead of the long syntax: array(). They do the exact same thing.
I also changed array_push() to a shorter version: $someArray[] =.
$result = array();
$resultArr['success'] =true;
while($row = mysqli_fetch_array($r))
{
array_push($result,array('$workOrderName'=>$row['workorder_name']));
}
$resultArr['result'] = $result;
echo json_encode($resultArr);
This will work fine.
Related
I'm trying to GET a JSON format back when I POST a specific ID to my database. As I get more than one result I have multiple rows, which I want to get back. I do get different arrays back, but it is not a valid JSON Format. Instead of
[{...},{...},{...}]
it comes back as
{...}{...}{...}
Therefore the [...] are missing and the arrays are not separated by commas.
My code is down below. The function "getUserBookingsKl" is defined in a different php.
//get user bookings
public function getUserBookingsKl($id) {
//sql command
$sql = "SELECT * FROM `***` WHERE `hf_id`=$id AND `alloc_to`>DATE(NOW()) AND NOT `confirmation`=0000-00-00 ORDER BY `alloc_from`";
//assign result we got from $sql to $result var
$result = $this->conn->query($sql);
// at least one result
if ($result !=null && (mysqli_num_rows($result) >= 1 ))
{
while ($row = $result->fetch_array())
{
$returArray[] = $row;
}
}
return $returArray;
}
...
...
foreach($userdb as $dataset)
{
$returnArray["group"] = $dataset["kf_id"];
$returnArray["from"] = $dataset["alloc_from"];
$returnArray["to"] = $dataset["alloc_to"];
echo json_encode($returnArray);
# return;
}
// Close connection after registration
$access->disconnect();
It looks like you're sequentially emitting the values, not pushing into an array. You need to make an array, push into it, then call json_encode on the resulting structure:
$final = [ ];
foreach ($userdb as $dataset)
{
$returnArray = [ ];
$returnArray["group"] = $dataset["kf_id"];
$returnArray["from"] = $dataset["alloc_from"];
$returnArray["to"] = $dataset["alloc_to"];
$final[] = $returnArray;
}
echo json_encode($final);
Note that it's important here to not use the same variable inside the loop each time through or you're just pushing the same array in multiple times.
I am new to PHP so far I managed to get the following output from database in JSON format.I created an array result which returns workorderName, but I want to get workOrderId also in the same array so that I can use it in android string request.
{
"result": [
{
"$workOrderName": "electrician"
},
{
"$workOrderName": "plumber"
},
{
"$workOrderName": "carpenter"
}
]
}
my php code is
<?PHP
require_once('connection.php');
$workName = "SELECT work_order_id,workorder_name FROM workorder_category";
$con=mysqli_connect($server_name,$user_name,$password,$db);
$r = mysqli_query($con,$workName);
$result = array();
$resultArr = array('success' => true);
while($row = mysqli_fetch_array($r)){
array_push($result,array('$workOrderName'=>$row['workorder_name']));
}
echo json_encode(array('result'=>$result));
mysqli_close($con);
?>
I want the Output like
{
"result": [
{
"$workOrderId":"1"
"$workOrderName": "electrician"
},
{
"$workOrderId":"2"
"$workOrderName": "plumber"
},
{
"$workOrderId":"3"
"$workOrderName": "carpenter"
}
]
}
I'm pretty sure you didn't mean to have the $ in the key, but this is easier and will give you the column names (work_order_id, workorder_name) from the table as keys. Make sure to use mysqli_fetch_assoc:
while($row = mysqli_fetch_assoc($r)){
$result[] = $row;
}
If you want to change the keys then you can alias them in the query and use the above:
$workName = "SELECT work_order_id AS workOrderID, workorder_name AS workOrderName FROM workorder_category";
Or you could build the array:
$result[] = array('workOrderID' => $row['work_order_id'],
'workOrderName' => $row['workorder_name']);
You need to tweak your code to add $workOrderId also in the array like below
array_push($result,array(
'$workOrderId' => $row['work_order_id']
'$workOrderName' => $row['workorder_name']
));
Hello Stackoverflow community, i'm little bit confused how i can achieve this. So this is how my json response should look:
some_array: [
{
some_json_object_atribute_1:
some_json_object_atribute_2:
// Here i need an array
json_array: [
]
}
{
some_json_object_atribute_1:
some_json_object_atribute_2:
}
]
But i'm only getting one row from json array. This is some part of the code:
$response["chat_rooms"] = array();
while ($chat_room = $result->fetch_assoc()) {
$tmp = array();
$tmp["chat_room_id"] = $chat_room["chat_room_id"];
$unread_messages = $db->getAllUnreadMsgsFromChatRoom($user_id, $chat_room["chat_room_id"]);
while ($unread_message = $unread_messages->fetch_assoc()) {
// Here i need one json array
$tmp["message_id"] = $unread_message["message_id"];
}
array_push($response["chat_rooms"], $tmp);
}
You are overriding $tmp["chat_room_id"] in every run of the while loop.
The right syntax would be:
$tmp["chat_room_id"][] = $unread_message["message_id"];
or
array_push($tmp["chat_room_id"], $unread_message["message_id"]);
I need to convert the below result. I generate this JSON array using PHP but now I need the same result into a single curly brace. Below is my PHP code to generate the JSON.
$arr = array();
#If no data was returned, check for any SQL errors
if ($res == false)
{
echo 'Query not Executed : '. die(print_r(sqlsrv_errors(), TRUE));
}
else
{
while($obj = sqlsrv_fetch_array($res, SQLSRV_FETCH_ASSOC))
{
$arr[] = array(
'code' => array_search($obj['name'], $countries_iso),
'total' => $obj['Total']
);
}
}
header("Content-type: application/json");
#Output the JSON data
print (json_encode($arr));
Output of above PHP code:
[
{
code: "AF",
total: 1
},
{
code: "DZ",
total: 1
},
{
code: "AS",
total: 2
}
]
But I want to show like below result:
{
"AF":1
"DZ": 1,
"AS": 2
}
I guess you want $arr[array_search($obj['name'], $countries_iso)] = $obj['Total'];
Your mistake was the fact that you were declaring a new array each time you add something to your original array. This way you assign the correct way :)
Try this code:
$arr = array();
#If no data was returned, check for any SQL errors
if ($res == false)
{
echo 'Query not Executed : '. die(print_r(sqlsrv_errors(), TRUE));
}
else
{
while($obj = sqlsrv_fetch_array($res, SQLSRV_FETCH_ASSOC))
{
$arr[array_search($obj['name'], $countries_iso)] = $obj['Total'];
}
}
header("Content-type: application/json");
#Output the JSON data
//$json = json_encode($arr);
$json = json_encode($arr);
Just do this:
$arr[array_search($obj['name'], $countries_iso)] = $obj['Total'];
But you can get rid of the whole array_search($obj['name'], $countries_iso) if you restrict the query to only return rows WHERE name IN (list of $countries_iso). Look up WHERE and IN for SQL Server.
You need to transform your data structure to an associative array, where the value you are currently storing in code will be the key and the value stored in total will be value.
I'll be able to help better if you post the code that generates your current JSON object
I use PHP to encode json data from my MySQL table, the output comes like this
[
{
"Copra_Crushed_MT": "2306.01851",
"Oil_Extracted_MT": "1454.9442"
},
{
"Copra_Crushed_MT": "1234",
"Oil_Extracted_MT": "5678"
},
{
"Copra_Crushed_MT": "1907",
"Oil_Extracted_MT": "4605"
}
]
But i want the structure to be this way, how should i proceed to get this
[
[2306.01851,1454.9442],
[1234,5678],
[1907,4605]
]
my PHP code used to encode JSON
private function productionhourlys(){
if($this->get_request_method() != "GET"){
$this->response('',406);
}
$query="SELECT distinct c.Copra_Crushed_MT, c.Oil_Extracted_MT FROM productionhourlys c order by c.productionhourlyNumber desc";
$r = $this->mysqli->query($query) or die($this->mysqli->error.__LINE__);
if($r->num_rows > 0){
$result = array();
while($row = $r->fetch_assoc()){
$result[] = $row;
}
$this->response($this->json($result), 200); // send user details
}
$this->response('',204); // If no records "No Content" status
}
private function json($data){
if(is_array($data)){
return json_encode($data);
}
}
Put array_values around your row:
$result[] = array_values($row);
(array_values docs)
Alternatively (and probably the better way) - You can use mysqli_result::fetch_row instead of fetch_assoc
while($row = $r->fetch_row()) {
(fetch_row docs)
json_encode in php will automatically turn associative arrays into json object (the curly brace syntax). You can use array values to remove keys and then json_encode will turn the arrays into JSON arrays (the square bracket syntax).