PHP - How to merge two different JSON outputs into one - php

My php server is generating two JSON output
1.] For MySql JSON printing I am using this code.
$sql = "select id ,Title , Meassage from lodhinews";
$result = $conn->query($sql);
$values = array();
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$values['data'][] = array(
'id'=>$row['id'],
'Title'=>$row['Title'],
'Meassage'=>$row['Meassage']
);
}
header('Content-Type: application/json;charset=utf-8');
echo json_encode($values ,JSON_PRETTY_PRINT);
} else {
$values = array(
'error'=>'No results found'
);
}
$conn->close();
?>
2.] For file name printing I am using this code
chdir('./uploads');
foreach(glob('*.*') as $filename){
$data[] = $filename;
}
echo json_encode($data);
?>
both the above code is working fine!
I wanted this both json output combined on one single page

not very complicated ! :)
$merged_array = array();
$merged_array[] = $data;
$merged_array[] = $values;
print json_encode($merged_array,JSON_PRETTY_PRINT);

Related

PHP show associative array content into JSON format

i'm new in PHP language. I'm writing a PHP script to get information from my online database(created on my altervista personal webpage) and convert in JSON format.
The problem is about when i get elements from my database i can show them correctly using "echo" command, but when i parse associative array to "json_encode" function i can't see correctly elements.
Here is the code:
$sql = "SELECT * FROM People";
$result = $conn->query($sql);
$json_array = array();
if ($result->num_rows > 0) {
// output data of each row
$row = $result->fetch_assoc();
foreach($row as $key => $value) {
echo "" . $key . ": " . $value;
echo "<br>";
$json_array[] = array(''=>$key, ''=>$value);
}
} else {
echo "0 results";
}
echo json_encode($json_array);
$conn->close();
?>
The $result->fetch_assoc(); returns an associative array.
As i said before i can see correct information using echo commands.
The problem is when i use this:
$json_array[] = array(''=>$key, ''=>$value);
The output is as follow:
[{"":"Mark"},{"":"ABC"},{"":"25"}]
Basically it's showing me only the second parameter "=>$value", while the first parameter "=>$key" is ignored.
Can you tell me please what should i change in order to see also the first parameter in my output?
Thanks
The correct way would be to do that
$json_array[] = array( $key => $value );
instead of
$json_array[] = array(''=>$key, ''=>$value);
You are essentially adding an EMPTY string as key and the $key as value at first, and then you replace it with the $value as they share the EMPTY string key in the array.
Read more at: http://php.net/manual/en/language.types.array.php#language.types.array.syntax.array-func
First param is ignored because it has the same key as the second (the key is ''), you should write:
$json_array[] = array($key, $value); // Indexed array
Output will be:
[["key1", "value1"],["key2", "value2"],["key3", "value3"]]
OR
$json_array[] = array($key => $value); // Associative array
Output will be:
[{"key1": "value1"},{"key2": "value2"},{"key3": "value3"}]
Try:
sql = "SELECT * FROM People";
$result = $conn->query($sql);
$json_array = array();
if ($result->num_rows > 0) {
// output data of each row
while ($row = $result->fetch_assoc()) {
$json_array[] = $row;
}
} else {
echo "0 results";
}
echo json_encode($json_array);
$conn->close();
In your code you are parsing only the first db result

how to fetch all rows from mysql using mysqli_fetch_assoc and convert to JSON

I have tried to get all the rows from mysql table for that am using mysqli_fetch_assoc. While using this am getting only one row. I need to convert the resulting array into JSON.
$query = "SELECT * FROM db_category WHERE publish='1'";
$result = mysqli_query($c, $query) or die(mysqli_error($c));
$length = mysqli_num_rows($result);
if($length > 0)
{
$var['status'] = 'success';
while($obj = mysqli_fetch_assoc($result))
{
$var = array_merge($var, $obj);
$var1 = json_encode($var);
}
echo '{"slider":['.$var1.']}';
}
else
{
$arr = array('status'=>"notfound");
echo '{"slider":['.json_encode($arr).']}';
}
Now the output for above code is,
{"slider":[{"status":"success","category_id":"12","category_name":"Books","publish":"1"}]}
Required output is,
{"slider":[{"status":"success","category_id":"1","category_name":"Apparel","publish":"1"},{"status":"success","category_id":"2","category_name":"Footwear","publish":"1"},{"status":"success","category_id":"3","category_name":"Furniture","publish":"1"},{"status":"success","category_id":"4","category_name":"Jewellery","publish":"1"}]}
How to solve this issue.
You can do it simply by json_encode() function. And you can also get all data into array, with mysqli_fetch_all() function :
$data = mysqli_fetch_all($result, MYSQLI_ASSOC);
$jsonData = json_encode(array('slider'=>$data, 'status' => 'success'));
If you want to put 'status'=>'success' for each row, do it like this (before json_encode)
foreach($data as $key => $dataRow) {
$data[$key]['status'] = 'success';
}

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

writing html tag into json response

CODE:
header('Content-type: text/plain');
if(mysql_num_rows($result))
{
while($post = mysql_fetch_assoc($result))
{
echo json_encode($post);
echo ',';
}
}
output:
{"id":"1","layartype":"college","attribution":"Daiict","title":"CEP
Daiict","latitude":"23.3400000000","longitude":"34.3334000000"},{"id":"2","layartype":"college","attribution":"Daiict","title":"Lab
Daiict","latitude":"23.4500000000","longitude":"34.0960000000"},
this json response in php i m getting in one line..this has actuallly 2 records..i want them to start in a new line....so what do i do?..html doesnot work i suppose.
This will send the correct content type for JSON and will send all results as a single JSON object (an array of your results).
header('Content-type: application/json');
$results = array();
if (mysql_num_rows($result)) {
while ($post = mysql_fetch_assoc($result)) {
$results[] = $post;
}
echo json_encode($results);
}

Categories