Codeigniter combine two array in foreach loop - php

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

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?

Nested array in json data in 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)]);

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

Php - creating json object

I am trying to create a json object from the data that I get from Ninja Forms that would look like this:
{
"title": "Contact Me",
"fields": [
{
"label": "Name",
"type": "textbox",
"required": "1"
},
{
"label": "Email",
"type": "email",
"required": "1"
}
]
}
I am trying to do so, like this:
$settings = ['label', 'type', 'required'];
$formTitle = Ninja_Forms()->form( 1 )->get()->get_setting('title');
$formFields = Ninja_Forms()->form(1)->get_fields();
$data = ['title' => $formTitle];
foreach ($formFields as $formField) {
$key = $formField->get_setting('key');
foreach ($settings as $setting) {
$data['fields'][$key][][$setting] = $formField->get_setting($setting);
}
}
return $data;
But, the result of that looks like this:
{
"title": "Contact Me",
"fields": {
"name": [
{ "label": "Name" },
{ "type": "textbox" },
{ "required": "1"}
],
"email": [
{ "label": "Email" },
{ "type": "email" },
{ "required": "1" }
],
How can I do this, so that the result looks like the one I have shown above?
I have also tried like this:
foreach ($settings as $setting) {
$data['fields'][] = $formField->get_setting($setting);
}
But, that gave me this kind of result:
{
"title": "Contact Me",
"fields": [
"Name",
"textbox",
"1",
"Email",
"email",
"1",
"Message",
"textarea",
"1",
"Submit",
"submit",
null
]
}
This gave me the wanted result:
foreach ($formFields as $formField) {
$key = $formField->get_setting('key');
foreach ($settings as $setting) {
$object[$setting] = $formField->get_setting($setting);
}
$data['fields'][] = $object;
}
return $data;
One way to look at this is to count the dimensions of the data. In your desired format, the deepest item is:
{ "fields": [ { "label": "Name"
So you have object -> array -> object.
If we indent each array in your code, we have:
$data // outermost array
['fields']
[$key]
[] // innermost array
[$setting] = $value; // key in innermost array
Or if we were to declare it with just one value:
$data = array(
'field' => array(
$key => array(
0 => array(
$setting => $value
)
)
)
);
So you have 4 levels of array, instead of 3.
Comparing to the JSON, taking an array with numeric keys as "array" and one with non-numeric keys as "object", the pattern is object -> object -> array -> object.
So it's the [$key] we need to eliminate, because it's creating an extra object dimension.
But we don't want to increment the key at [] for each item either, so we need to either make our value in advance...
foreach ($settings as $setting) {
$object[$setting] = $formField->get_setting($setting);
}
$data['fields'][] = $object;
...or choose our key in advance:
$i++;
foreach ($settings as $setting) {
$data['fields'][$i] = $formField->get_setting($setting);
}

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