PHP create nested array and pass back with json_encode - php

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);

Related

How to covert php data into json format?

Here i am fetching data using php code.But i want the same code to be convert into json format.I am not getting the way to do it.
I have tried it in this way.
my code
while ($rows = mysql_fetch_array($filter)) {
$result['name'] = $rows['name'];
$result['id'] = $rows['id'];
}
$res = json_encode($result);
print_r($res);
getting result
{"name":["sradha","nicky","demo","testing"],"id":["1","2","3","4"]}
Here i want it in this below json format
[{id:1, name:'sradha'},
{id:2, name:'nicky'},
{id:3, name:'demo'},
{id:3, name:'testing'}];
Please suggest me.
Any suggestion will highly appreciate.
Thank you in advance.
Try below:
while ($rows = mysql_fetch_assoc($filter)) {
$result['name'] = $rows['name'];
$result['id'] = $rows['id'];
$new_result[] = $result;
}
$res = json_encode($new_result);
print_r($res);
OR
while ($rows = mysql_fetch_assoc($filter)) {
$result[] = $rows;
}
$res = json_encode($result);
print_r($res);
Try this
$result = array();
while ($rows = mysql_fetch_assoc($filter)) {
$result[] = $rows;
}
echo json_encode($result);
Create your array like this
$i=0;
while($rows = mysql_fetch_array($filter)) {
$result[$i]['name'] = $rows['name'];
$result[$i]['id'] = $rows['id'];
$i++;
}
$res = json_encode($result);
print_r($res);
It will return output result

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);
}
}

trouble with array push in php

I have a problem with array push.I cant get the all data from the array array.I want to get like this format.
[["username","average"],["aa",2.34],["bb",6.7],["hh",9.8]]
here is my code
while($acc_rs = mysql_fetch_array($acc_qry))
{
$acc_cnt = $acc_rs['Total_login'];
$time_stamp = $acc_rs['last_logged'];
$avg_login = $acc_rs['avg'];
$name = $acc_rs['name'];
$ji = array();
$sal = array("username","average");
$kk = array($name,$avg_login);
array_push($ji,$sal,$kk);
}
array_push($da,$new,$average);
$result = array(array('username', 'average'));
while ($row = mysql_fetch_assoc($acc_qry)) {
$result[] = array($row['name'], $row['avg']);
}
echo json_encode($result);

Return In JSON Format, 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.. :-)

add php function to json array before encoding

$selected_offer = $_POST['selected_offer'];
$get_categories = $db->query("SELECT oc_id, oc_name FROM object_category WHERE oc_relate = '".$selected_offer."'");
$json = array();
while ($get_rows = mysql_fetch_array($get_categories, MYSQL_ASSOC)) {
$json[] = $get_rows;
}
echo json_encode($json);
return;
I toke this code from someone else and since I am not familiar with json I am asking here at stackoverflow how can add a function to the oc_name attribute before the json encodes it and still return the same struckture as it is now, like for example:
language($get_rows['oc_name'])
while ($get_rows = mysql_fetch_array($get_categories, MYSQL_ASSOC)) {
$get_rows['oc_name'] = language($get_rows['oc_name']);
$json[] = $get_rows;
}
You can apply your function on the mentioned field before you add the row in your $json array
$json = array();
while ($get_rows = mysql_fetch_array($get_categories, MYSQL_ASSOC)) {
$get_rows['oc_name']=language($get_rows['oc_name']);
$json[] = $get_rows;
}

Categories