Return valid Json array - php

I'm fairly new to Json and arrays and I'm just wondering whether someone can correct the code I've tried that is still outputting an invalid string.
$json = array(
'posts' => array(),
);
while($row = mysqli_fetch_array($result)) {
$posts = array();
$posts['count'] = $rowcount;
$posts['streamitem_id'] = $row['streamitem_id'];
$json['posts'] = $posts;
echo json_encode($json);
}
I have used http://jsonlint.com/ and posted my returned data from firebug errors on lines 6,11 and 16
} {
{
"posts": {
"count": 4,
"streamitem_id": "1976"
}
} {
"posts": {
"count": 4,
"streamitem_id": "1980"
}
} {
"posts": {
"count": 4,
"streamitem_id": "1099"
}
} {
"posts": {
"count": 4,
"streamitem_id": "1178"
}
}

Some have already commented with a valid answer however, I believe array_push is the most efficient method rather than redefining the $posts variable over and over.
$json = array(
'posts' => array()
);
while($row = mysqli_fetch_array($result)) {
array_push($json['posts'], $array(
'count' => $rowcount,
'streamitem_id' => $row['streamitem_id']
)
);
}
echo json_encode($json);
PS: I noticed that you're putting $rowcount in each post array. If this is not intended, I recommend the following change:
$json = array(
'posts' => array(),
'count' => $rowcount
);
And then in the while loop:
array_push($json['posts'], $array(
'streamitem_id' => $row['streamitem_id']
)
);
This way, you can reference the post count and it won't be a waste of memory.
console.log(json['count']);

I think you want this:
$posts = array();
$rowcount = 0;
while ($row = mysqli_fetch_array($result)) {
$posts[] = array(
'count' => $rowcount,
'streamitem_id' = $row['streamitem_id'],
);
$rowcount++;
}
$json['posts'] = $posts;
echo json_encode($json);

Put this outside of loop, you are overwriting and echoing each value instead whole at once
Inside loop
$posts[] = ["count"=> $rowcount,"streamitem_id"=>$row['streamitem_id']);
After loop
$json['posts'] = $posts;
echo json_encode($json);

Related

How to change result in array?

i have a array result like this
{"data":{"NamaKecamatan":"BEJI","total":"2","laki":"1","cewe":"1"}}
{"data":{"NamaKecamatan":"BOJONGSARI","total":0,"laki":0,"cewe":0}}
{"data":{"NamaKecamatan":"CILODONG","total":"2","laki":"1","cewe":"1"}}
{"data":{"NamaKecamatan":"CIMANGGIS","total":"4","laki":"2","cewe":"2"}}
but i want to change array like this:
data: [{NamaKecamatan: "BEJI", total: "46", laki: "18", cewe: "28"},…]
0: {NamaKecamatan: "BEJI", total: "46", laki: "18", cewe: "28"}
1: {NamaKecamatan: "BOJONGSARI", total: "20", laki: "7", cewe: "13"}
2: {NamaKecamatan: "CILODONG", total: "93", laki: "48", cewe: "45"}
3: {NamaKecamatan: "CIMANGGIS", total: "96", laki: "47", cewe: "49"}
4: {NamaKecamatan: "CINERE", total: "13", laki: "7", cewe: "6"}]
this is my controller in php
public function countByKecamatan(){
$kecamatan = $this->db->query("SELECT IDKecamatan, NamaKecamatan FROM mskecamatan ORDER BY NamaKecamatan ASC")->result_array();
foreach ($kecamatan as $keykecamatan) {
$result = $this->MsLaporan->dataNullByKecamatan($dateStart, $dateEnd, $kategori, $keykecamatan['IDKecamatan']);
if ($result == NULL) {
$row = array(
"NamaKecamatan" => $keykecamatan['NamaKecamatan'],
"total" => 0,
"laki" => 0,
"cewe" => 0,
);
}else{
$row = $result[0];
}
$data = array(
"data" => $row,
);
echo json_encode($data);
}
}
please help me to change this data
$data = '[{"data":{"NamaKecamatan":"BEJI","total":"2","laki":"1","cewe":"1"}},
{"data":{"NamaKecamatan":"BOJONGSARI","total":0,"laki":0,"cewe":0}},
{"data":{"NamaKecamatan":"CILODONG","total":"2","laki":"1","cewe":"1"}},
{"data":{"NamaKecamatan":"CIMANGGIS","total":"4","laki":"2","cewe":"2"}}]';
$array_data = json_decode($data, ture);
$result = [];
foreach($array_data as $item) {
$result['data'][] = $item['data'];
}
return json_encode($result);
You can approach this as following
public function countByKecamatan(){
$kecamatan = $this->db->query("SELECT IDKecamatan, NamaKecamatan FROM mskecamatan ORDER BY NamaKecamatan ASC")->result_array();
$i = 0;
foreach ($kecamatan as $keykecamatan) {
$result = $this->MsLaporan->dataNullByKecamatan($dateStart, $dateEnd, $kategori, $keykecamatan['IDKecamatan']);
if ($result == NULL) {
$row = array(
"NamaKecamatan" => $keykecamatan['NamaKecamatan'],
"total" => 0,
"laki" => 0,
"cewe" => 0,
);
}else{
$row = $result[0];
}
($i > 0) ? ($data[] = $row) : ($data = array('data' => $row));
$i++;
}
echo json_encode($data);
}
The output your getting is down to 2 minor problems in the lines...
$data = array(
"data" => $row,
);
echo json_encode($data);
The first is that you are building the array with the extra level which you say you want to remove. The second line of code then echos each piece of data one at a time. You need to build up a list of all of the records and then return the full data in one go.
public function countByKecamatan(){
// Create empty array for data
$data = [];
$kecamatan = $this->db->query("SELECT IDKecamatan, NamaKecamatan FROM mskecamatan ORDER BY NamaKecamatan ASC")->result_array();
foreach ($kecamatan as $keykecamatan) {
$result = $this->MsLaporan->dataNullByKecamatan($dateStart, $dateEnd, $kategori, $keykecamatan['IDKecamatan']);
if ($result == NULL) {
$row = array(
"NamaKecamatan" => $keykecamatan['NamaKecamatan'],
"total" => 0,
"laki" => 0,
"cewe" => 0,
);
}else{
$row = $result[0];
}
// Add new row of data to data to be returned
$data[] = $row;
}
// Return all of the data in JSON format
return json_encode($data);
}
Note that this returns the value rather than echos it - you may need to change this if when you call the controller, your framework needs to encode it some other way (i.e. as part of a Response object).

How to encode json with multiple rows?

Before I begin, I have looked through other examples and Q&A's on multiple platforms but none of them seem to solve my problem. I am trying to return multiple rows from MySQL via a json. However, I have been unable to. The code below shows my attempt.
I get my responses via Postman. The first while returns only the last entry in the database, and the do-while returns all entries but doesn't encode the json properly, as the json outputs syntax error but the html part shows all entries.
<?php
$dashboard_content_token = $_REQUEST["dashboard_content_token"];
$token = "g4";
require(cc_scripts/connect.php);
$sql = "SELECT * FROM `dashboard_content`";
$check = strcmp("$token", "$dashboard_content_token");
$statement = mysqli_query($con, $sql);
if (check) {
$rows = mysqli_fetch_assoc($statement);
if (!$rows) {
echo "No results!";
} else {
while ($rows = mysqli_fetch_assoc($statement)) {
$news_id = $rows['news_id'];
$image_url = $rows['image_url'];
$news_title = $rows['news_title'];
$news_description = $rows['news_description'];
$news_article = $rows['news_article'];
$result['dashboard content: '][] = array('news_id' => $news_id, 'image_url' => $image_url, 'news_title' => $news_title, 'news_description' => $news_description, 'news_article' => $news_article);
echo json_encode($result);
}
// do {
// $news_id = $rows['news_id'];
// $image_url = $rows['image_url'];
// $news_title = $rows['news_title'];
// $news_description = $rows['news_description'];
// $news_article = $rows['news_article'];
// $result['dashboard content: '][] = array('news_id' => $news_id, 'image_url' => $image_url, 'news_title' => $news_title, 'news_description' => $news_description, 'news_article' => $news_article);
// echo json_encode($result);
// } while ($rows = mysqli_fetch_assoc($statement));
mysqli_free_result($statement);
}
}
?>
This should work. You'll want to use the do...while statement otherwise the first result is skipped.
<?php
$dashboard_content_token = $_REQUEST["dashboard_content_token"];
$token = "g4";
require(cc_scripts/connect.php);
$sql = "SELECT * FROM `dashboard_content`";
$check = strcmp("$token", "$dashboard_content_token");
$statement = mysqli_query($con, $sql);
if (check) {
$rows = mysqli_fetch_assoc($statement);
if (!$rows) {
echo "No results!";
} else {
do {
$news_id = $rows['news_id'];
$image_url = $rows['image_url'];
$news_title = $rows['news_title'];
$news_description = $rows['news_description'];
$news_article = $rows['news_article'];
$result['dashboard content: '][] = array('news_id' => $news_id, 'image_url' => $image_url, 'news_title' => $news_title, 'news_description' => $news_description, 'news_article' => $news_article);
} while ($rows = mysqli_fetch_assoc($statement));
mysqli_free_result($statement);
echo json_encode($result);
}
}
?>
The key is to put all of you results into an array and then just do one json_encode(). When you call json_encode() multiple times, your API will return invalid json.
In your while loop,
$result['dashboard content: '] = array('news_id' => $news_id, 'image_url' => $image_url, 'news_title' => $news_title, 'news_description' => $news_description, 'news_article' => $news_article);
just over-writes the same "dashboard content" entry in the $result array every time you run the loop. This is why you only see the last entry.
Doing json_encode() within the loop makes no sense as well, because you'll just output multiple, disconnected individual JSON objects, which are not part of an array or coherent structure. This doesn't make for a valid JSON response.
It's not abundantly clear exactly what output structure you're hoping for, but this might give you either a solution, or at least a shove in the right direction:
$statement = mysqli_query($con, $sql);
$result = array("dashboard_content" => array()); //create an associative array with a property called "dashboard_content", which is an array. (json_encode will convert an associative array to a JSON object)
if (check) {
$rows = mysqli_fetch_assoc($statement);
if (!$rows) {
echo "No results!";
} else {
while ($rows = mysqli_fetch_assoc($statement)) {
$news_id = $rows['news_id'];
$image_url = $rows['image_url'];
$news_title = $rows['news_title'];
$news_description = $rows['news_description'];
$news_article = $rows['news_article'];
//append the current data to a new entry in the "dashboard_content" array
$result["dashboard_content"][] = array('news_id' => $news_id, 'image_url' => $image_url, 'news_title' => $news_title, 'news_description' => $news_description, 'news_article' => $news_article);
}
}
//now, output the whole completed result to one single, coherent, valid JSON array.
echo json_encode($result);
You should end up with some JSON like this:
{
"dashboard_content": [
{
"news_id": 1,
"image_url": "abc",
"news_title": "xyz",
//...etc
},
{
"news_id": 2,
"image_url": "def",
"news_title": "pqr",
//...etc
},
//...etc
]
}

Encode nested JSON array in php

I want to send nested JSON array.Which contain following format.
${"posts":[{
"abc":"123",
"xyz":"123",
"pro":[{
"name":"Brinjal",
"qty":"500 gms"
},
{
"name":"Brinjal",
"qty":"500 gms"
}]
}]
}
Here is my php code:
$rows = $stmt->fetchAll();
if ($rows) {
$order["posts"] = array();
foreach ($rows as $row) {
$post = array();
$post["order_id"] = $row["order_id"];
$post["order_totalamount"] = $row["order_totalamount"];
$post["address"] = $row["address"];
$post["pincode"] = $row["pincode"];
$post["delivery_timeslot"] = $row["delivery_timeslot"];
$post["order_date"] = $row["order_date"];
$query1= "query";
$rows1 = $stmt->fetchAll();
if ($rows1) {
foreach ($rows1 as $row1) {
$query2= "query";
$rows2 = $stmt->fetchAll();
$post["product"] = array();
if ($rows2) {
$products = array();
foreach ($rows2 as $row2) {
$products["product_name"]=$row2["product_name"];
$products["prod_qty"] = $row2["product_minquantity"];
}
array_push($post["product"],$products);
echo json_encode($products);
}
}
}
array_push($order["posts"], $post);
}
echo json_encode($order);
}
From above code I got result:
$ {"posts":
[{
"order_id":"18",
"order_totalamount":"40",
"address":"2, Chetan Society, Vadodara",
"pincode":"390023",
"delivery_timeslot":"Zone wise delivery",
"order_date":"2016-03-18 17:50:53",
"product":[{"product_name":"Brinjal","prod_qty":"500 gms"}]
}]
}
But my actual product array is:
${"product_name":"Banana","prod_qty":"1 Kg"}{"product_name":"Brinjal","prod_qty":"500 gms"}
Kindly help out. I am stuck on it. tried a lot but did not get success.
In
foreach ($rows2 as $row2) {
$products["product_name"]=$row2["product_name"];
$products["prod_qty"] = $row2["product_minquantity"];
}
You overwrite $products["product_name"]and $products["prod_qty"] with the values of the last $row2.
The line {"product_name":"Banana","prod_qty":"1 Kg"}{"product_name":"Brinjal","prod_qty":"500 gms"} actually consists of two echo's:
{"product_name":"Banana","prod_qty":"1 Kg"}
{"product_name":"Brinjal","prod_qty":"500 gms"}
But you don't see the difference. I suggest echoing a string in-between them or use something like var_dump() to see how many values you're echoing.
You should do something like:
for ($i = 0; $i < count($rows2); $i++) {
$products[$i]["product_name"]=$rows2[$i]["product_name"];
$products[$i]["prod_qty"] = $rows2[$i]["product_minquantity"];
}
This will result in: [{"product_name":"Banana","prod_qty":"1 Kg"},{"product_name":"Brinjal","prod_qty":"500 gms"}]
FYI $array[] = has the same rsults as array_push(), but had less overhead of calling array_push().
EDIT:
Below a complete example since it doesn't seem to workout for you:
//Demo $order
$order = array (
'posts' =>
array (
0 =>
array (
'order_id' => '18',
'order_totalamount' => '40',
'address' => '2, Chetan Society, Vadodara',
'pincode' => '390023',
'delivery_timeslot' => 'Zone wise delivery',
'order_date' => '2016-03-18 17:50:53',
),
),
);
//Demo $rows2
$rows2 = array(
array(
'product_name' => 'banana',
'product_minquantity' => '1 Kg'
),
array(
'product_name' => 'Brinjal',
'product_minquantity' => '500 gms'
)
);
$post['product'] = array();
if ($rows2) {
$products = array();
for ($i = 0; $i < count($rows2); $i++) {
$products[$i]['product_name'] = $rows2[$i]['product_name'];
$products[$i]['prod_qty'] = $rows2[$i]['product_minquantity'];
}
$post['product'] = $products;
echo json_encode($products); //[{"product_name":"banana","prod_qty":"1 Kg"},{"product_name":"Brinjal","prod_qty":"500 gms"}]
}
//$order['posts'][] = $post;
$order['posts'][0] = $order['posts'][0] + $post;
//In this example I only have 1 item in $order['posts'] so I know to add to key 0.
//In your case you need to know which key of $rows1 you need to do the adding.
//Change the foreach loop of $rows to a for loop as well so you can define your own keynames ($i).
echo '<br>==================================================================<br>';
echo json_encode($order);
/*
{
"posts":[
{
"order_id":"18",
"order_totalamount":"40",
"address":"2, Chetan Society, Vadodara",
"pincode":"390023",
"delivery_timeslot":"Zone wise delivery",
"order_date":"2016-03-18 17:50:53",
"product":[
{
"product_name":"banana",
"prod_qty":"1 Kg"
},
{
"product_name":"Brinjal",
"prod_qty":"500 gms"
}
]
}
]
}
*/

Function not returning all database rows

I have this function in Code igniter PHP where I am trying to get all rows from the database that match a input value.
How should I change the code to get all rows that match my search criteria?
Thank you
Model search function:
function findquestion($searchvalue){
$this->db->where('answer1', $searchvalue);
$res = $this->db->get('questions');
$count = $res->num_rows();
if($res->num_rows()==0){
return "...";
}
$moviearray = $res->row_array();
return $moviearray;
}
Controller Function:
public function getdatabasedata()
{
if($this->input->server('REQUEST_METHOD') == 'GET')
{
$year = $this->input->get('searchvalue');
if($year != ''){
$movie = $this->adminmodel->findquestion($year);
echo json_encode($movie);
}
}
}
When I look at Postman to check what the JSON object holds, this is what I get. But in fact I have three more rows in my database that match my search criteria.
{
"id": "10",
"question": "test questions",
"image": "test image",
"answer1": "answer1",
"answer2": "answer2",
"answer3": "answer3",
"answer4": "answer4"
}
function findquestion($searchvalue){
1) define array.
$data = array();
$this->db->where('answer1', $searchvalue);
$res = $this->db->get('questions');
if($res->num_rows()==0){
return "...";
}
2) loop trough results and store in array.
foreach ($res->result() as $row)
{
$data[] = array(
'id' => $row->id,
'question' => $row->question,
'image' => $row->image,
'answer1' => $row->answer1,
'answer2' => $row->answer2,
'answer3' => $row->answer3,
'answer4' => $row->answer4
);
}
//$moviearray = $res->row_array();
return $data;
}

Php json generation for multiple records

I am trying to create a json using php
while ($info = mysqli_fetch_array($result,MYSQLI_ASSOC))
{
$id = stripslashes($info['id']);
$pricedol = stripslashes($info['pricedol']);
$final_result = array('id' => $id,'pricedol' => $pricedol );
}
$json = json_encode($final_result);
echo $json;
This is giving the following output
{
"id": 14567,
"pricedol": 15.57
}
But i have couple of records in the db...i want the following output
{
"id": 14567,
"pricedol": 15.57
},
{
"id": 4567,
"pricedol": 55.25
},
One more thing...do i need to serialize before parsing in jquery
You could create a multi-dimensional array and use json_encode on that array:
$final_result = array();
while ($info = mysqli_fetch_array($result,MYSQLI_ASSOC))
{
$id = stripslashes($info['id']);
$pricedol = stripslashes($info['pricedol']);
$final_result[] = array('id' => $id,'pricedol' => $pricedol);
}
$json = json_encode($final_result);
echo $json;

Categories