Nested array in json data in php - php

I need to show Mysql data in json nested array like
{
"status": true,
"categories": [
{
"id": "1",
"title": "Title 1",
},
{
"id": "2",
"title": "Title 2",
},
{
"id": "3",
"title": "Title 3",
}
]
}
Code I am trying is
$sql = "SELECT * FROM `categories`";
$res_data = mysqli_query($conn,$sql);
$rows = array();
while($row = mysqli_fetch_array($res_data)){
$rows[] = $row;
foreach($rows as $row){
$rows = ['id' => $row['id'], 'title' => $row['title']];
}
}
$data = array('status' => true, 'categories' => array($rows));
echo json_encode($data);
But what I get is only with one record in the nested array i.e
{
"status": true,
"categories": [
{
"id": "1",
"title": "Title 1",
}
]
}
How can I achieve my requirement?

If you want to avoid duplication, leave out the foreach loop and just write in the while loop:
$rows[] = ['id' => $ row ['id'], 'title' => $ row ['title']];
…because with the while loop, you already run through the row array.

You don't need any loops. Mysqli already returns a nested array which you can directly output to JSON
$res_data = $conn->query("SELECT id, title FROM `categories`")
echo json_encode(['status' => true, 'categories' => $res_data->fetch_all(MYSQLI_ASSOC)]);

Related

List online users and get total "talep" count each user

I have a table for Talepler and Yonetim. Now Each talepler has his own users. and each user is mapped to that talepler by a field called user id. So how i can print out online users with total count in Talepler table by Count(*) with Join query.
Here my code with helper function. But i want with join.
$this->db->select('yonetim.id, yonetim.user, yonetim.onoff');
$this->db->from('yonetim');
$this->db->where('yonetim.onoff',1);
$query = $this->db->get();
$datam = array();
foreach ($query->result() as $data) {
$count = checkIfuserMax($data->id);
if($talepsay < 10 ) {
$datam[] = array(
'id' => $data->id,
'user' => $data->user,
'onoff' => $data->onoff,
'toplamtalep' => $count
);
}
}
echo json_encode($datam);
and here my helper function
function checkIfuserMax($id) {
$ci =& get_instance();
$ci->db->select('COUNT(*) as toplam');
$ci->db->where(array( 'hangiadmin' => $id, 'onaylayan' => null));
$ci->db->from('talepler');
$query = $ci->db->get();
$result = $query->result();
return $result[0]->toplam;
}
Finally here my json result
[
{
"id": "1",
"user": "user1",
"onoff": "1",
"toplamtalep": "13"
},
{
"id": "2",
"user": "user2",
"onoff": "1",
"toplamtalep": "0"
},
{
"id": "4",
"user": "user3",
"onoff": "1",
"toplamtalep": "2"
},
{
"id": "173",
"user": "user4",
"onoff": "1",
"toplamtalep": "6"
}
]
This code working properly. But i want to make this same result with "JOIN" query. Could you please help me about this query?

Append JSON code to a JSON created from MySQL and PHP

I am trying to create dynamically a JSON from a MySQL, which seems fairly easy with this piece of code I found in this thread Create nested json object using php mysql.
However, I want to add before and after the $json_response some piece of JSON code.
The main code
$result = mysql_query("SELECT * FROM Places ");
$json_response = array(); //Create an array
while ($row = mysql_fetch_array($result))
{
$row_array = array();
$row_array['title'] = $row['title'];
$row_array['image_url'] = $row['image_url'];
$row_array['subtitle'] = $row['subtitle'];
$row_array['buttons'] = array();
$id = $row['id'];
$option_qry = mysql_query("SELECT * FROM Places where id=$id");
while ($opt_fet = mysql_fetch_array($option_qry))
{
$row_array['buttons'][] = array(
'type' => $opt_fet['type'],
'caption' => $opt_fet['caption'],
'url' => $opt_fet['url'],
);
}
array_push($json_response, $row_array); //push the values in the array
}
echo json_encode($json_response, JSON_PRETTY_PRINT);
Produces this JSON
[
{
"title": "Name of the place",
"image_url": "image.jpg",
"subtitle":Additional info",
"buttons": [
{
"type": "'url'",
"caption": "More Info",
"url": "https://some link "
}
]
},
{
"title": "Name of the place 2",
"image_url": "image2.jpg",
"subtitle":Additional info2",
"buttons": [
{
"type": "'url'",
"caption": "More Info",
"url": "https://some link 2"
}
]
}
]
I have somehow to add the following code before the already created JSON
{
"version": "v2",
"content": {
"messages": [
{
"type": "cards",
"elements":
And this code in the end
}
]
}
}
Pretty simple:
$final_json = [
"version" => "v2",
"content" => [
"messages" => [[
"type" => "cards",
"elements" => $json_response
]]
]
];
echo json_encode($final_json, JSON_PRETTY_PRINT);
Personally, I'd rename $json_response to $messages for clarity purposes.
While declaring array $json_response = array(); you can actually prepare it with your default values require like
$stdObj=new \stdClass();
$stdObj->version="V2";
$stdObj->content=(object)["messages"=>(object)["type"=>'cards','elements'=>$row_array['buttons']]];
echo json_encode($stdObj, JSON_PRETTY_PRINT);

merge array keys and add the values-PHP

I want to merge two same keys in an array and get the sum of the values.
I want the same structure as it is now.Because this data needs to be converted to JSON.
This is what i get now.
{
"data": [{
"count_of_invites": 5,
"user": "Rajesh",
"id": "53"
},
{
"count_of_invites": 9,
"user": "Student",
"id": "45"
},
{
"count_of_invites": 4,
"user": "Student",
"id": "45"
}
]
}
As you can see the id 45 are repeated.As i want the result as,
Expected output
{
"data": [{
"count_of_invites": 5,
"user": "Rajesh",
"id": "53"
},
{
"count_of_invites": 13,
"user": "Student",
"id": "45"
}
]
}
As you can see the duplicate entry should be removed as well as the count_of_invites of duplicate entry should be added.
<?php
$data = [
[
'id' => 2,
'name' => 'Paul',
'count' => 4
],
[
'id' => 3,
'name' => 'Peter',
'count' => 5
],
[
'id' => 3,
'name' => 'Peter',
'count' => 7
]
];
foreach($data as $array)
$counts[$array['id']][] = $array['count'];
$counts = array_map('array_sum', $counts);
foreach($data as $k => $array)
$data[$k]['count'] = $counts[$array['id']];
$data = array_unique($data, SORT_REGULAR);
print json_encode($data, JSON_PRETTY_PRINT);
Output:
[
{
"id": 2,
"name": "Paul",
"count": 4
},
{
"id": 3,
"name": "Peter",
"count": 12
}
]
You can achieve it this way:
$ids = array();
$output = array();
foreach ($input as $value) {
if (!isset($ids[$value["id"]])) {
$ids[$value["id"]]=$count($output);
$output[]=$value;
} else {
$output[$ids[$value["id"]]]["count_of_invites"] = $value["count_of_invites"];
$output[$ids[$value["id"]]]["user"] = $value["user"];
}
}
The count method was declared as variable and i've added with addition assignment operator.
Thank You for helping.
$ids = array();
$output = array();
foreach ($response as $value) {
if (!isset($ids[$value["id"]])) {
$ids[$value["id"]] = count($output);
$output[] = $value;
}
else {
$output[$ids[$value["id"]]]["count_of_invites"] += $value["count_of_invites"];
$output[$ids[$value["id"]]]["user"] = $value["user"];
}
}

Codeigniter combine two array in foreach loop

I have problem to combining two array, here my sample code
$arr1 = [];
$data = $this->db->query("SELECT QUERY");
foreach ($data->result_array() as $row) {
$arr1[] = array(
"type" => "column",
"name" => $row['name'],
"legendText" => $row['name'],
"showInLegend" => true
);
}
$count = $this->db->query("SELECT QUERY");
foreach ($count->result_array() as $rows) {
$arr1[]["dataPoints"] = array(
"label" => $rows['data']
);
}
With this code, result is
[
{
"type": "column",
"name": "LA 1",
"legendText": "LA 1",
"showInLegend": true
},
{
"dataPoints": {
"label": "1"
}
}
]
I want to combine two array, So the output should be like this:
[
{
"type": "column",
"name": "LA 1",
"legendText": "LA 1",
"showInLegend": true,
"dataPoints": [{
"label": "1"
}]
}
]
Please someone help me to find out the easiest way to solve this issue.
The proper way to fix this would be to change your database queries to one which would return all the information in a single query.
$data = $this->db->query("SELECT a.*, b.datapoints FROM table1 a, table2 b....");

mixare json, how to configure?

$query = "SELECT id, latitude, longitude, elevation, title, distance, has_detail_webpage, webpage, info FROM korban";
$q=mysql_query($query);
//echo $query;
while($e=mysql_fetch_assoc($q))
$output[]=$e;
print(json_encode($output));
From this code, it will generate like this,
[
{"id":"1","latitude":"-77.036519","longitude":"77.036519","elevation":"0","title":"coba","distance":null,"has_detail_webpage":"0","webpage":"0","info":"0"},
{"id":"3","latitude":"12","longitude":"42","elevation":"21","title":"213","distance":"12","has_detail_webpage":"1","webpage":"12","info":"12"},
{"id":"32","latitude":"","longitude":"","elevation":null,"title":null,"distance":null,"has_detail_webpage":"1","webpage":null,"info":null}
]
But I want something like this,
{ "status": "OK", "num_results": 3, "results":
[ { "id": "2833", "lat": "41.359288", "lng": "-73.646850", "elevation": "53", "title": "Target4", "distance": "1.756", "has_detail_page": "1", "webpage": "" },
{ "id": "2821", "lat": "41.359768", "lng": "-73.646870", "elevation": "0", "title": "Target2", "distance": "1.771", "has_detail_page": "0", "webpage": "" },
{ "id": "2829", "lat": "41.359820", "lng": "-73.646870", "elevation": "0", "title": "Target3", "distance": "1.545", "has_detail_page": "1", "webpage": "" }
] }
How can I do it?
Fetch all your results or do it row by row. Choose yourself. En create the json array afterwards. You also might want to look at your use of mysql_* functions. As they are deprecated now. And you should really switch to MySQli/PDO
$result = array();
while($row = mysql_fetch_assoc($q)) {
$result[] = $row;
}
$output = array('status' => 'OK' , 'num_results' => count($result), 'results' => $result);
echo json_encode($output);
To add the structure you wish to have in your json, first you must create that structure from php before encoding it to json.
$objects = array();
while ($r = mysql_fetch_associ($rs) {
$a = new stdClass();
$a->status = $r['status'];
...
$a->results = array('id' => $r['id']....)
$objects[] = $a;
}
echo json_encode($objects);
$query = "SELECT id, latitude, longitude, elevation, title, distance, has_detail_webpage, webpage, info FROM korban";
$q=mysql_query($query);
$output = array();
if($q) {
$output['status'] = 'OK';
}
$output['num_results'] = mysql_num_rows($q);
while($e=mysql_fetch_assoc($q)) {
$output['results'][]= array (
'id' => $e['id'],
'lat' => $e['latitude'],
'lng' => $e['longitude'],
'elevation' => $e['elevation'],
'title' => $e['title'],
'distance' => $e['distance'],
'has_detail_page' => $e['has_detail_webpage'],
'webpage' => $e['webpage'],
);
}
print(json_encode($output));

Categories