Return In JSON Format, PHP - php

In a project, I have to return user_id, user_age from the database and the return format should be like
user object which contains user_id and user_age
average age of users
count of users
the return format should be in JSON format.
I have created user array and encoded to JSON by using the method
json_encode(user);
my code is like this :
while ($row = mysql_fetch_array($result)) {
$user["id"] = $row["id"];
$user["name"] = ucfirst($row["user_name"]);
$user["date"] = $row["date_of_treatment"];
$user["age"] = $row["age_of_user"];
// push single user into final response array
array_push($response, $user);
$count = $count+1;
$sum_of_age = $sum_of_age+$row["age_of_user"];
}
echo json_encode($response);
I have calculated the average age ($sum_of_age/$count) and count of returned users ($count), but I don't know how to return average age and count of users with the same json response.any help will be appreciated.

You can do like this:
$count=0;
$sum_of_age=0;
$response=array();
$response['users']=array();
while ($row = mysql_fetch_array($result)) {
$user["id"] = $row["id"];
$user["name"] = ucfirst($row["user_name"]);
$user["date"] = $row["date_of_treatment"];
$user["age"] = $row["age_of_user"];
// push single user into final response array
array_push($response['users'], $user);
$count = $count+1;
$sum_of_age = $sum_of_age+$row["age_of_user"];
}
$response['count']=$count;
$response['avg']=$sum_of_age/$count;
echo json_encode($response);

You can try this:
$users = array();
$sum_of_age = 0;
$count = 0;
$users = array();
while ($row = mysql_fetch_array($result))
{
$user["id"] = $row["id"];
$user["name"] = ucfirst($row["user_name"]);
$user["date"] = $row["date_of_treatment"];
$user["age"] = $row["age_of_user"];
// push single user into final response array
$users[] = $user;
$count++;
$sum_of_age += (int) $row["age_of_user"];
}
$response = array(
'users' => $users,
'averageAge' => $sum_of_age/$count,
'count' => $count
);
echo json_encode($response);
This should result in the following json response:
{
"users":[
{ "id" : "1", "name" : "John Doe" , "date" : "2014-03-22 15:20" , "age" : 42 },
{...},
...
],
"averageAge": 42,
"count": 1337
}

<?php
$response = array();
while ($row = mysql_fetch_array($result)) {
$user["id"] = $row["id"];
$user["name"] = ucfirst($row["user_name"]);
$user["date"] = $row["date_of_treatment"];
$user["age"] = $row["age_of_user"];
// push single user into final response array
array_push($response, $user);
$count = $count+1;
$sum_of_age = $sum_of_age+$row["age_of_user"];
}
$response["average_age"] = $sum_of_age / $count;
$response["count"] = $count;
echo json_encode($response);
}
This is the answer, thanks #Amal Murali (commented a link), the link you have provided is working.. :-)

Related

Pushing into array does not give required result

$output["data"] = array();
// after fetching data form db
while($row = $stmt->fetch()){
$output["data"][] = [
$row['inventory_order_id'],
$row['inventory_order_name'],
$row['inventory_order_total'],
$row['inventory_order_date'],
];
if(($_SESSION['user_type'] == 'user'){
$output['data'][] = 'user';
}
}// end while loop
and gives this result:
{"data":[[1,"1","Hina","10000.00","2021-01-11 15:01:54"],"user"]}
but i need result like following:
{"data":[[1,"1","Hina","10000.00","2021-01-11 15:01:54","user"]]}
user should be in same array
You need to define a reuse the same key. In your current code new key for user is used.
$i = 0;
while($row = $stmt->fetch()){
$output["data"][$i] = [
$row['inventory_order_id'],
$row['inventory_order_name'],
$row['inventory_order_total'],
$row['inventory_order_date'],
];
if (($_SESSION['user_type'] == 'user')) {
$output['data'][$i] = 'user';
}
$i++;
}

Convert JSON from MySQL to PHP

So i have this JSON in my MySQL Database
{
"11011001": {
"id": 11011001,
"name": "Test",
"price": 4,
"inCart": 7
}
}
Now i want to work with this data in PHP.
I got the JSON by doing this in PHP:
$sql = "SELECT article FROM test WHERE id = '$id'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$row = $result->fetch_assoc();
$aricle = $row["article"];
} else {
echo "Something went wrong";
}
After that i did this which resulted in getting a JSON Array:
$tarray = json_decode($article, TRUE);
What can i do now to get the values from the JSON?
For example i want the value of the price in a variable called $price.
$price = $tarray[11011001]['price'];
Or you can loop through the results if you have many articles
$tarray = json_decode($json,true);
foreach ($tarray as $index => $item)
{
$price[] = $item['price'];
}
var_dump($price);
Assuming you might have a collection of items, you can map the ids to prices with array_column.
<?php
$json =<<<JSON
{
"11011001": {
"id": 11011001,
"name": "Test",
"price": 4,
"inCart": 7
}
}
JSON;
$items = json_decode($json, TRUE);
$ids_prices = array_column($items, 'price', 'id');
var_export($ids_prices);
Output:
array (
11011001 => 4,
)
Only one item, but you don't know the key up front?
if(count($items) === 1) {
$item = array_pop($items);
$price = $item['price'];
}
echo $price;
Output:
4
First you have a sql injection, you must create a prepared query if you have data from users.
$sql = "SELECT article FROM test WHERE id = :id";
$query = $con->prepare($sql);
$query->bindValue(":id", $id);
$query->execute();
$result = $query->fetch();
if ($result) {
// $article will be stdClass if json correct
$article = json_decode($result['article']);
$price = $article->price;
// or $article = json_decode($result['article'], true);
// $price = $article['price'];
}
Just an example

Array json from php is not output in the corect way

I'm trying to make a json output from my db in php with all of users from sql table but i don't know how to do that..i'm new with this.
I want the code to output like this.
[
{
"name": "Maybell",
"avatar": "zeldman/128.jpg",
"data": {
"company": "Alibaba",
"title": "Engineer"
}
}
]
but the my code does the following output and is not ok.
{
"name": "Maybell",
"avatar": "zeldman\/128.jpg",
"company": "alibaba"
"title": "Engineer"
}
Here is the Php code:
<?php
header("Content-type: text/json");
$db = mysqli_connect("localhost","root","","testest");
//MSG
$query = "SELECT * FROM mls_users LIMIT 20";
$result = mysqli_query($db, $query);
//Add all records to an array
$rows = array();
while($row = $result->fetch_array()){
$name = $row['name'];
$avatar = $row['avatar'];
$company= $row['company'];
$title= $row['title'];
}
//Return result to jTable
$qryResult = array();
$qryResult['name'] = $name;
$qryResult['avatar'] = $avatar;
$qryResult['company'] = $company;
$qryResult['title'] = $title;
echo json_encode($qryResult,JSON_PRETTY_PRINT);
mysqli_close($db);
?>
Just change:
//Add all records to an array
$rows = array();
while($row = $result->fetch_array()){
$name = $row['name'];
$avatar = $row['avatar'];
$company= $row['company'];
$title= $row['title'];
}
//Return result to jTable
$qryResult = array();
$qryResult['name'] = $name;
$qryResult['avatar'] = $avatar;
$qryResult['company'] = $company;
$qryResult['title'] = $title;
To:
//Add all records to an array
$qryResult = [];
while ($row = $result->fetch_array()) {
$qryResult[] = [
'name' => $row['name'],
'avatar' => $row['avatar'],
'data' => [
'company' => $row['company'],
'title' => $row['title'],
],
];
}
You can skip setting the intermediate variables and just add onto the $qryResult array directly.
try this:
<?php
header("Content-type: text/json");
$db = mysqli_connect("localhost","root","","testest");
//MSG
$query = "SELECT * FROM mls_users LIMIT 20";
$result = mysqli_query($db, $query);
//Add all records to an array
$users = array();
while($row = $result->mysqli_fetch_assoc()){
$users[] = [
'name' => $row['name'],
'avatar' => $row['avatar'],
'data' => [
'company' => $row['company'],
'title' => $row['title']
]
]
}
echo json_encode($users,JSON_PRETTY_PRINT);
mysqli_close($db);
?>
I changed fetch_row() to mysqli_fetch_assoc() and then actually made an array with all fetched rows. You kind of wanted to do that i can see that in comments but you didnt. Then just json encode it.
The outlining brackets [ and ] should come automatically when the array has multiple elements in it.
You are almost there, you just need to wrap it in an array and make data an array.
$qryResult = array();
$qryResult['name'] = $name;
$qryResult['avatar'] = $avatar;
// Now make an array to hold data
$data = array();
$data['company'] = $company;
$data['title'] = $title;
// Add data to qryResult
$qryResult['data'] = $data
// Wrap qryResult in array so output will be wrapped in array
$outPutResults = array($qryResult);
echo json_encode($outPutResults,JSON_PRETTY_PRINT);
$qryResult = array();
$qryResult['name'] = $name;
$qryResult['avatar'] = $avatar;
$qryResult['data']['company'] = $company;
$qryResult['data']['title'] = $title;
Try that way. You are asking for a multidimensional-array so you need to set it up as one.

Json wont response my array in php

I am trying to fetch multiple rows from my database and then encode them with json so I can access them in my Android application. I've successfully encoded an object but I couldn't find a way to do the same with an array. My code looks like:
if ($tag == 'friends') {
$id = $_POST['id'];
$friends = $db->getMyFriends($id);
if ($friends != false) {
// friends found
$result[] = array();
while($row = mysql_fetch_assoc($friends)){
$response[ "error"] = FALSE;
$result[] = array(
$response["friends"]["unique_id"] = $row["unique_id"],
$response["friends"]["name"] = $row["name"],
$response["friends"]["email"] = $row["email"]);
}
echo json_encode($response);
}
The code from getMyFriends($id) I have already tested and it works fine. It returns :
$result = mysql_fetch_array($result);
return $result;
When using a rest client passing the parameters:
Tag: friends
id: $id
this is the json response that I get:
{
"tag": "myfriends",
"error": false
}
, but no actual database data.
If anyone knows what I'm doing wrong, I'd really appreciate it, I've been browsing the internet for hours now.
If getMyFriends already have a $result = mysql_fetch_array($result);you don't need to fetch again.
You could simply:
$friends = $db->getMyFriends($id);
echo json_encode($friends);
But that will only return one friend, if you want all remove $result = mysql_fetch_array($result); from getMyFriends and return the pure mysql_result, then do something like:
$result = array();
while($row = mysql_fetch_assoc($friends)){
array_push($result,$row);
}
echo json_encode($result);
I tried this and it worked.
if($tag=='friends'){
$id = $_REQUEST['id'];
$friends = $db->getMyFriends($id);
if ($friends != false) {
// friends found
$result[] = array();
while($row = mysql_fetch_assoc($friends)){
$response[ "error"] = FALSE;
$result[] = array(
$response["friends"]["unique_id"] = $row["id"],
$response["friends"]["name"] = $row["name"],
$response["friends"]["email"] = $row["email"]
);
}
echo json_encode($result);
}
}

PHP create nested array and pass back with json_encode

I have the following, and while $data['details'] is being populated OK, there should be three results in $data['tests'], but "tests" isn't showing at all in the JSON result:
{"details":["Clinical result","Signature result"]}
$data = array();
while ($row = mysql_fetch_array($result)) {
$data['details'] = array($row['tests_clinical'], $row['signature']);
foreach($row['lab_test_group_fk'] as $group){
$data['tests'] = array($group);
}
}
echo json_encode($data);
If I change the above to the following then I get only the last record for $row['lab_test_group_fk'], not all three records for that column (hence the foreach loop as above):
while ($row = mysql_fetch_array($result)) {
$data['details'] = array($row['tests_clinical'], $row['signature']);
$data['tests'] = array($row['lab_test_group_fk']);
}
echo json_encode($data);
{"details":["Clinical result","Signature result"],"tests":["21"]}
What am I doing wrong here?
Thanks to Tamil Selvin this was the solution that worked for me:
$data = array();
while ($row = mysql_fetch_array($result)) {
$data['details'] = array($row['tests_clinical'], $row['signature']);
$data['tests'][] = array($row['lab_test_group_fk']);
}
echo json_encode($data);
Which returned:
{"details":["Clinical result","Signature result"],"tests":[["31"],["2"],["21"]]}
Try
$data = array();
while ($row = mysql_fetch_array($result)) {
$data[]['details'] = array($row['tests_clinical'], $row['signature']);
$data[]['tests'] = array($row['lab_test_group_fk']);
}
echo json_encode($data);
or
while ($row = mysql_fetch_array($result)) {
$data[] = array(
'details' => array($row['tests_clinical'], $row['signature']),
'tests' => array($row['lab_test_group_fk'])
);
}
echo json_encode($data);
$data['tests'] = array($group); means reassign $data['tests'] to a new value again.
Try $data['tests'][] = array($group); .
You are overwriting existing data of $data. You need some kind of array where you will put all your records. Try this
$data = array();
while ($row = mysql_fetch_array($result)) {
$record = array(); // this creates new record
$record['details'] = array($row['tests_clinical'], $row['signature']);
foreach($row['lab_test_group_fk'] as $group){
$record['tests'] = array($group);
}
$data[] = $record; // this adds record to data
}
echo json_encode($data);

Categories