PHP Echo json_encode - php

I am having a small problem, I am showing json using PHP, I have this code:
foreach($result as $r){
$returnEcho["Id"] = $r["id"];
$returnEcho["Username"] = $r["username"];
$returnEcho["Email"] = $r["email"];
$returnEcho["Info"] = $r["Info"];
echo json_encode($returnEcho);
The problem with this code is, it will display the JSON like this:
{"Username":"X","Email":"X","Info":"X"}
{"Username":"X","Email":"X","Info":"X"}
{"Username":"X","Email":"X","Info":"X"}
But what I want is something like this:
[
{
"Username":"X",
"Email":"X",
"Info":"X"
},
{
"Username":"X",
"Email":"X",
"Info":"X"
}
]
How can I do this?
Thanks.

You have to build everything in an array and echo the json only after foreach finish. Like this:
$return = [];
foreach($result as $r){
$returnEcho["Id"] = $r["id"];
$returnEcho["Username"] = $r["username"];
$returnEcho["Email"] = $r["email"];
$returnEcho["Info"] = $r["Info"];
$return[] = $returnEcho;
}
echo json_encode($return);

Related

correct way to return a json_object as an array

I have an array populated using an sql statement in the following manner:
$index = 0;
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC))
{
$bookname[$index] = ($row['Bookname']);
$subjectname[$index] = ($row['SubjectName']);
$index++;
}
When I go to echo json encode the Arrays I get a blank [] when I know it has been populated which is really weird.
Am I doing anything wrong in my context
echo json_encode($Bookname,$SubjectName);
You can use json_encode as like that:
<?php
$index = 0;
$data = array();
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC))
{
$data[$index]['bookname'] = $row['Bookname'];
$data[$index]['subjectname'] = $row['SubjectName'];
$index++;
}
json_encode($data); // encode your array
?>
Try following:
$index = 0;
$data = array();
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC))
{
$data['Bookname'][$index] = $row['Bookname']
$data['SubjectName'][$index] = $row['SubjectName'];
$index++;
}
echo json_encode($data);
You have passed two parameter while calling json_encode function. You batter combine two array in one. Then call the json_encode function like json_encode($combinedArray)

How to format this in php side

I want to output like this
[
['Alice', 'Mike'],
['Bob', 'Jim'],
['Carol', 'Bob']
]
but i could not get the format
here is my code
$cmd = $this->connection->prepare('SELECT emp,manager from department');
$cmd->execute();
$records = $cmd->fetchAll(PDO::FETCH_ASSOC);
foreach($records as $row) {
$rowdata=$row;
}
$return_data = array($rowdata);
echo json_encode($return_data);
Thank you in advance
update: Answer
$rowdata=array_values($row);
Thank you #Ja͢ck
Try this:
$records = $cmd->fetchAll(PDO::FETCH_NUM);
foreach($records as $row) {
$rowdata[] = array_values($row);
}
If you use <pre> tags around the array and use print_r() to print it, it will come out as very readable.
Here you can check
foreach($records as $row) {
$rowdata[]=$row;
}
$return_value=array_chunk($rowdata,2);
echo json_encode($return_value);
Update :
$cmd = $this->connection->prepare('SELECT emp,manager from department');
$cmd->execute();
$records = $cmd->fetchAll(PDO::FETCH_OBJ);
$rowdata=array();
foreach($records as $record) {
$rowdata[] = array($record->em.','.$record->manager);
}
$return_data = $rowdata;
echo json_encode($return_data);

Count how many of the same element in json

Im parsing json with php in this simple piece of code
<?php
$json = file_get_contents('list.json');
$data = json_decode($json,true);
$records=$data['records'];
foreach($records as $record)
{
echo $record['number']." ".$record['opened_at'];
}
?>
But i want to echo how many 'number' element are in my json file exemple bellow
{
"records":[
{
"number":"INC018****",
},
{
"number":"INC018****",
},
{
"number":"INC018****",
},
{
"number":"INC018****",
},
<?php
$json = file_get_contents('list.json');
$data = json_decode($json,true);
$records=$data['records'];
$numberCount = 0;
foreach($records as $record)
{
$numberCount += isset($record['number']); // Here we go
echo $record['number']." ".$record['opened_at'];
}
echo $numberCount;
?>
This function might be helpful: http://www.php.net/manual/en/function.array-count-values.php
$counts = array_count_values($records);
$numberCount = $counts['number'];

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

Fetch, Decode and Re-encode JSON

I am attempting to fetch JSON from Instagram according to a number of URL parameters, the JSON is then decoded and then the objects required are then encoded into my own JSON format. Whilst I know this sound a little ridiculous, it is what is required. My only issue here is that for some reason it does not encode each section of JSON, it will only work for one item. The code is as below.
<?php
function instagram($count=16){
$igtoken = $_GET['igtoken'];
$hashtag = $_GET['hashtag'];
$url = 'https://api.instagram.com/v1/tags/'.$hashtag.'/media/recent/?access_token='.$igtoken.'&count='.$count;
$jsonData = json_decode((file_get_contents($url)));
$jsonData = json_decode((file_get_contents($url)));
foreach ($jsonData->data as $key=>$value) {
$response = array();
$response["data"] = array();
$data = array();
$data["createdtime"] = $value->caption->created_time;
$data["username"] = $value->caption->from->username;
$data["profileimage"] = $value->caption->from->profile_picture;
$data["caption"] = $value->caption->text;
$data["postimage"] = $value->images->standard_resolution->url;
array_push($response["data"], $data);
$result = json_encode($response);
}
return $result;
}
echo instagram();
?>
It will work for each section of JSON if I do something like this instead:
$result .= '<li>
'.$value->caption->from->username.'<br/>
'.$value->caption->from->profile_picture.'<br/>
'.$value->caption->text.'<br/>
'.$value->images->standard_resolution->url.'<br/>
'.$value->caption->created_time.'<br/>
</li>';
I feel I have bodged up somewhere with the array, however i'm not entirely sure.
What if we move $response["data"] and $result varia out of foreach?
Have you tried this?
$response = array();
$response["data"] = array();
foreach ($jsonData->data as $key=>$value) {
$data = array();
$data["createdtime"] = $value->caption->created_time;
$data["username"] = $value->caption->from->username;
$data["profileimage"] = $value->caption->from->profile_picture;
$data["caption"] = $value->caption->text;
$data["postimage"] = $value->images->standard_resolution->url;
array_push($response["data"], $data);
}
$result = json_encode($response);
return $result;

Categories