My PHP Code is the following, I need some assistance please:
//DB connection
$result = mysqli_query($con,"SELECT * FROM `clients`");
$info = array();
$count = 0;
$meta = array('page' => 1, 'pages' => 1, 'perpage' => -1, 'total' => 14, 'sort' => "asc", 'field' => "ID");
while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
$info[$row['clientid']]['id'] = $row['id'];
$info[$row['clientid']]['name'] = $row['name'];
$info[$row['clientid']]['email'] = $row['email'];
$info[$row['clientid']]['cell'] = $row['cell'];
$count++;
}
$data = json_encode(array_values($info));
echo $data;
My Result;
[{"ID":1,"name":"A","email":"a#a.com","cell":"082"},
{"ID":2,"name":"B","email":"b#b.com","cell":"083"},
{"ID":3,"name":"C","email":"c#c.com","cell":"079"}]
The JSON should add the meta array with the following result:
{"meta":
{"page": 1,"pages": 1,"perpage": -1,"total": 3,"sort": "asc","field": ID"},
"data": [{"ID":1,"name":"A","email":"a#a.com","cell":"082"},
{"ID":2,"name":"B","email":"b#b.com","cell":"083"},
{"ID":3,"name":"C","email":"c#c.com","cell":"079"}]
},
Create array of required structure and json_encode it:
$data = json_encode(array(
'meta' => $meta,
'data' => array_values($info),
));
Related
I want to create json which contains all orders from datebase. I tried to write this code but it returns only one order.
$query = mysql_query("SELECT * FROM orders WHERE id_user = '".$userdata['user_login']."' ORDER BY `nom` ASC ");
if ($query)
{
$i = 0;
while ($row = mysql_fetch_assoc($query))
{
$where=$row["where"];
$time_min=$row["time_min"];
$time_max=$row["time_max"];
$date1=$row["date1"];
$date2=$row["date2"];
$from=$row["from"];
$id=$row["id"];
$orders =[
'from' => $from,
'where' => $where,
'time_min' => $time_min,
'time_max' => $time_max,
'date1' => $date1,
'date2' => $date2,
'id' => $id];
$i++;
}
}
$data = [
'count' =>$i,
'orders' => $orders
];
header('Content-type: application/json');
echo json_encode( $data );
exit;
Now the response looks like this:
But I want like this:
Append to the $orders array:
$query = mysql_query("SELECT * FROM orders WHERE id_user = '".$userdata['user_login']."' ORDER BY `nom` ASC ");
if ($query)
{
$i = 0;
while ($row = mysql_fetch_assoc($query))
{
$where=$row["where"];
$time_min=$row["time_min"];
$time_max=$row["time_max"];
$date1=$row["date1"];
$date2=$row["date2"];
$from=$row["from"];
$id=$row["id"];
$orders[] =[ // <--- The difference
'from' => $from,
'where' => $where,
'time_min' => $time_min,
'time_max' => $time_max,
'date1' => $date1,
'date2' => $date2,
'id' => $id];
$i++;
}
}
$data = [
'count' =>$i,
'orders' => $orders
];
header('Content-type: application/json');
echo json_encode( $data );
exit;
here i m doing a json_encode
public function get_posts_for_category($user_id,$category_id,$page)
{
$cat_id = $this->ApiModel->get_category_id($category_id);
$total_row = $this->ApiModel->get_category_posts_count($cat_id->category);
$per_page = 2;
$total_pages = $total_row / $per_page;
$posts = $this->ApiModel->get_category_posts($cat_id->category,$per_page,$page);
$data = array();
foreach($posts as $post)
{
$fav = $this->ApiModel->get_favourite($user_id,$post->pid);
if($fav == 1)
{
$status = 'true';
}
else
{
$status = 'false';
}
$array = array('pid' => $post->pid, 'uid' => $post->uid, 'title' => $post->title, 'slug' => $post->slug, 'content' => $post->content, 'image' => $post->image, 'time_stamp' => $post->time_stamp);
$data[] = array('page' => $page, 'posts' => $array, 'is_favorite' => $status);
}
echo strip_tags(json_encode($data));
}
the output i m getting from the above code is
But i want some thing like this
<?php
public function get_posts_for_category($user_id,$category_id,$page)
{
$cat_id = $this->ApiModel->get_category_id($category_id);
$total_row = $this->ApiModel->get_category_posts_count($cat_id->category);
$per_page = 2;
$total_pages = $total_row / $per_page;
$posts = $this->ApiModel->get_category_posts($cat_id->category,$per_page,$page);
$data = array();
foreach($posts as $post)
{
$fav = $this->ApiModel->get_favourite($user_id,$post->pid);
if($fav == 1)
{
$status = 'true';
}
else
{
$status = 'false';
}
$array = array('pid' => $post->pid, 'uid' => $post->uid, 'title' => $post->title, 'slug' => $post->slug, 'content' => $post->content, 'image' => $post->image, 'time_stamp' => $post->time_stamp, 'is_favorite' => $status);
$data[] = array('page' => $page, 'posts' => $array, 'total_posts' => count($posts), 'total_pages' => $total_pages);
}
echo strip_tags(json_encode($data));
}
?>
$return = array(
'page' => $page,
'total_posts' => $total_row,
'total_page' => $total_pages,
);
$data = [];
foreach($posts as $post)
{
$fav = $this->ApiModel->get_favourite($user_id, $post->pid);
if($fav == 1)
{
$status = 'true';
}
else
{
$status = 'false';
}
$array = array('pid' => $post->pid, 'uid' => $post->uid, 'title' => $post->title, 'slug' => $post->slug, 'content' => $post->content, 'image' => $post->image, 'time_stamp' => $post->time_stamp, 'is_favorite' => $status);
$data[] = $array;
}
$return['posts'] = $data;
$this->output->set_content_type('application/json');
$this->output->set_output(json_encode($return));
just replace this code with your foreach & echo statement.
You never should use strip_tags in conjunction with json_encode because you are already encoding the data it's receivers choice to do whatever he wants also in this process you might break the encoding.
Also you should use CI output library to send response you must not echo anything from your controller. see here https://ellislab.com/codeigniter/user-guide/libraries/output.html for more details
If you would like the numeric values to be output as such, (instead of strings) you may wish to try:
json_encode($return, JSON_NUMERIC_CHECK);
To format the outputted JSON nicely (indentation etc) use:
json_encode($return, JSON_PRETTY_PRINT);
You can use various combinations of the above as per json_encode's options.
As for the boolean values (instead of "true" and "false" returned as strings), you'll need to cast them as boolean types first:
$status = (bool) true;
I am trying to get some data that I have called from a mySQL database to correctly display in a GeoJSON format. Here's some of my PHP code:
$data = array(); //setting up an empty PHP array for the data to go into
if($result = mysqli_query($db,$query)) {
while ($row = mysqli_fetch_assoc($result))
{
$data[] = $row;
}
}
$jsonData =json_encode($data);
$original_data = json_decode($jsonData, true);
$coordinates = array();
foreach($original_data as $key => $value) {
$coordinates[] = array($value['latitude'], $value['longitude']);
}
$new_data = array(
'type' => 'FeatureCollection',
'features' => array(array(
'type' => 'Feature',
'properties' => array('time' => $value['time']),
'geometry' => array('type' => 'Point', 'coordinates' => $coordinates),
),
),
);
$final_data = json_encode($new_data, JSON_PRETTY_PRINT);
print_r($final_data);
I've managed to get my results to look like this so far:
But I need them to look like this so that every set of coordinates has its own "type" and "properties" key-value pair:
I've already found some help with this issue here, but I just can't manage to get over this last formatting hurdle...
Instead of building coordinates, you need to build features:
$data = array(); //setting up an empty PHP array for the data to go into
if($result = mysqli_query($db,$query)) {
while ($row = mysqli_fetch_assoc($result))
{
$data[] = $row;
}
}
$jsonData =json_encode($data);
$original_data = json_decode($jsonData, true);
$features = array();
foreach($original_data as $key => $value) {
$features[] = array(
'type' => 'Feature',
'properties' => array('time' => $value['time']),
'geometry' => array(
'type' => 'Point',
'coordinates' => array(
$value['latitude'],
$value['longitude'],
1
),
),
);
}
$new_data = array(
'type' => 'FeatureCollection',
'features' => $features,
);
$final_data = json_encode($new_data, JSON_PRETTY_PRINT);
print_r($final_data);
I was searching for a solution for my problem.
I have the code below:
while($row = mysql_fetch_array($resultQuery)){
$response = array(
'name' => $row['name'],
'data' => $row['data']
);
$responses[] = $response;
}
echo json_encode($responses);
The code will bring this result:
[{"name":"Name001","data":"1"},
{"name":"Name001","data":"2"},
{"name":"Name001","data":"3"},
{"name":"Name002","data":"4"},
{"name":"Name002","data":"5"},
{"name":"Name002","data":"6"}]
But I would like to have the result below:
[{"name":"Name001","data":[1,2,3]},
{"name":"Name002","data":[4,5,5]}
Each "Name" has its own ID, I would like in the "while" put each id with its own data.
Thank you for your help.
1. Update:
$id_name = "xx";
while($row = mysql_fetch_array($resultQuery)){
if($id !== $row['id']){
$response = array(
'name' => $row['name'],
'data' => array($row['data'])
);
$responses[] = $response;
}
$id_name = $row['id'];
}
echo json_encode($responses);
I am trying to check the ID first and if is different will bring to me:
[{"name":"Name001","data":["1"]},{"name":"Name002","data":["4"]}]
while($row = mysql_fetch_array($resultQuery))
$tmp[$row['name']][] = $row['data'];
foreach($tmp as $key => $item)
$responses[] = array('name' => $key, 'data' => $item);
echo json_encode($responses);
result
[{"name":"Name001","data":["1","2","3"]},{"name":"Name002","data":["4","5","6"]}]
I made a test here, hope you like.
$arr = array();
$arr[] = array(
'name' => 'val',
'data' => array(1, 2, 3)
);
$arr[] = array(
'name' => 'val',
'data' => array(1, 2, 3)
);
echo json_encode($arr);
Output:
[{"name":"val","data":[1,2,3]},{"name":"val","data":[1,2,3]}]
How to make from this:
{"color":[{"id":"41","name":"red"}]}
{"color":[{"id":"19","name":"blue"}]}
...
this thing by php and json_encode
{"color":[{"id":"41","name":"red"},{"id":"19","name":"blue"},...]}
Data come from DB and I use folowing code:
$json = array();
$jsonRow= array();
while ($row = mysqli_fetch_array($getResult)) {
$jsonRow = array(
$row['color'] => array(
array(
"id" => $row['id'],
"name" => $row['name'],
)
)
);
array_push($json,$jsonRow);
}
$arr= array();
$jsonRow= array();
while ($row = mysqli_fetch_array($getResult)) {
$jsonRow = array(
"id" => $row['id'],
"name" => $row['name'],
);
$arr[]=$jsonRow;
}
$json = json_encode(array('color'=>$arr));
echo $json;
How about this?
$json = array();
$colors= array();
while ($row = mysqli_fetch_array($getResult)) {
array_push($colors,
array(
"id" => $row['id'],
"name" => $row['name'],
)
);
$json = array( "colors" => $colors);
}
Try this:
$json = array();
$jsonRow= array();
while ($row = mysqli_fetch_array($getResult)) {
$jsonRow[] = array(
"id" => $row['id'],
"name" => $row['name'],
);
}
// color can be $row['color']
// If its constant, I am not sure if its a good idea to keep in the loop.
$json = array("color" => $jsonRow);
echo json_encode($json);