How to merge MySQL query result with JSON format - php

Hi i am trying to merge output of MySQL result in JSON format but i confused how i can do this so guys i need your helps please tell me how i can do this work thank you.
SQL:
$result = $db->sql_query("SELECT a.*,i.member_id,i.members_seo_name
FROM ".TBL_IPB_USER." i
LEFT JOIN ".TBL_IPB_LA." a
ON a.member_id=i.member_id
WHERE i.".$column." = '".$val."' AND a.game = '".$game."'");
while( $dbarray = $db->sql_fetchrow($result) ){
$arr[] = $dbarray;
}
return ($arr);
The normal result and output with JSON format for my query is:
{
"status": 200,
"result": [
{
"member_id": "1",
"member_name": "maxdom",
"ip_address": "177.68.246.162",
"session_onlineplay": "1",
"sid": "IR63374a32d1424b9288c5f2a5ce161d",
"xuid": "0110000100000001",
"serialnumber": "9923806a06b7f700a6ef607099cb71c6",
"game": "PlusMW3",
"members_seo_name": "maxdom"
},
{
"member_id": "1",
"member_name": "maxdom",
"ip_address": "81.254.186.210",
"session_onlineplay": "1",
"sid": "IR3cd62da2f143e7b5c8f652d32ed314",
"xuid": "0110000100000001",
"serialnumber": "978e2b2668ec26e77c40c760f89c7b31",
"game": "PlusMW3",
"members_seo_name": "maxdom"
}
],
"handle": "checkUSER"
}
But i want to merge output and result like this one:
{
"status": 200,
"result": [
{
"member_id": "1",
"member_name": "maxdom",
"ip_address": [
"177.68.246.162",
"81.254.186.210"
],
"session_onlineplay": "1",
"sid": [
"IR63374a32d1424b9288c5f2a5ce161d",
"IR3cd62da2f143e7b5c8f652d32ed314"
],
"xuid": "0110000100000001",
"serialnumber": [
"9923806a06b7f700a6ef607099cb71c6",
"978e2b2668ec26e77c40c760f89c7b31"
],
"game": "PlusMW3",
"members_seo_name": "maxdom"
}
],
"handle": "checkUSER"
}

you better use php for your parser, prevent high load for database, this is sample code
$result = $db->sql_query("SELECT a.*,i.member_id,i.members_seo_name
FROM ".TBL_IPB_USER." i
LEFT JOIN ".TBL_IPB_LA." a
ON a.member_id=i.member_id
WHERE i.".$column." = '".$val."' AND a.game = '".$game."'");
$arr = array();
while( $dbarray = $db->sql_fetchrow($result) ){
$item = $dbarray;
$item['ip_address'] = array($item['ip_address']);
$item['sid'] = array($item['sid']);
$item['serialnumber'] = array($item['serialnumber']);
$index = $dbarray['member_id'];
if(isset($arr[$index]))
{
$arr[$index]['ip_address'] = array_merge($arr[$index]['ip_address'], $item['ip_address'];
$arr[$index]['sid'] = array_merge($arr[$index]['sid'], $item['sid'];
$arr[$index]['serialnumber'] = array_merge($arr[$index]['serialnumber'], $item['serialnumber']);
} else {
$arr[$index] = $item;
}
}
return array_values($arr);

Related

make json array in json codeigniter

please help, i got stucked on making json using codeigniter.
this is what i want my json look like
{
"pelajar": [
{
"id": "1",
"name": "rumah sakit",
"usia": "45",
"tahun": "2020",
"alamat": "jalan kartini"
},
{
"id": "2",
"name": "rumah sakit umum",
"usia": "28",
"tahun": "2020",
"alamat": "jalan ibu",
"pendidikan": [
{
"id_pelajar": "2",
"sekolah": "SDN Lombok timur"
},
{
"id_pelajar": "2",
"sekolah": "SMPN Lombok timur"
}
]
}
]
}
but, i dont know why my code doesnt work to make like it.
this is how my code output :
{
"pelajar": {
"pelajar": [
{
"id": "1",
"name": "rumah sakit",
"usia": "45",
"tahun": "2020",
"alamat": "jalan kartini"
},
{
"id": "2",
"name": "rumah sakit umum",
"usia": "28",
"tahun": "2020",
"alamat": "jalan ibu"
}
],
"pendidikan": [
{
"id_pelajar": "2",
"sekolah": "SDN Lombok timur"
},
{
"id_pelajar": "2",
"sekolah": "SMPN Lombok timur"
}
]
}
}
this is my code :
$query = $this->db->query("select * from learn") -> result();
$response = array();
$data = array();
$datap = array();
foreach($query as $row){
$data[] = array(
"id"=> $row->id,
"name"=>$row->name,
"usia"=>$row->usia,
"tahun"=>$row->tahun,
"alamat"=>$row->alamat
);
$id = $row->id;
$pendidikanquery = $this->db->query("select * from pendidikan where learn_id='$id'" ) -> result();
foreach($pendidikanquery as $pen){
$datap[] = array(
"id_pelajar"=> $pen->id_pelajar,
"sekolah"=> $pen->sekolah
);
}
}
}
$response['pelajar']['pelajar'] = $data;
$response['pelajar']['pendidikan'] = $datap;
header('Content-Type: application/json');
echo json_encode($response, TRUE);
my problem is to set 'pendidikan' in the pelajar list where id_pelajar from pendidikan is same with id from pelajar table.
Honestly, there is so much to fix, this script should probably be completely rewritten, but I am not prepared to do that from my phone.
I would recommend using Active Record techniques in your model (not your controller).
Cache the subarray data before pushing into the first level. In doing so, you maintain the relationship between the parent id and the subarray data.
To be clear, my snippet will always create a pendidikan subarray -- even if it has no data. If you do not want this behavior, you will need to modify the script to check if the subarray is empty and then conditionally include it into the parent array. If this was my project, I would prefer a consistent data structure so that subsequent process wouldn't need to check again if specific keys exist.
Untested code:
$query = $this->db->query("SELECT * FROM learn")->result();
$data = [];
foreach($query as $row){
$datap = [];
$pendidikanquery = $this->db->query("SELECT * FROM pendidikan WHERE learn_id = {$row->id}")->result();
foreach ($pendidikanquery as $pen) {
$datap[] = [
"id_pelajar" => $pen->id_pelajar,
"sekolah" => $pen->sekolah
];
}
$data[] = [
"id" => $row->id,
"name" => $row->name,
"usia" => $row->usia,
"tahun" => $row->tahun,
"alamat" => $row->alamat,
"pendidikan" => $datap
];
}
header('Content-Type: application/json');
echo json_encode(["pelajar" => $data]);
if you want the output like your first image(the one with a red square)-
$response['pelajar']['pendidikan'] = $datap; // change this one to
// this ↓↓
$response['pelajar']['pelajar']['pendidikan'] = $datap; // change it like this

create tree view like json from existing combined array

I have one combined array of order and its items combined into one array but i am trying to create json structure like order then its items list like wise.
$combinedarray[]=array('orderid'=>1,'partycode'=>10,"item"=>'abc',"price"=>250);
$combinedarray[]=array('orderid'=>1,'partycode'=>10,"item"=>'xyz',"price"=>250);
$combinedarray[]=array('orderid'=>2,'partycode'=>20,"item"=>'pqr',"price"=>250);
$combinedarray[]=array('orderid'=>2,'partycode'=>20,"item"=>'lmn',"price"=>250);
Output should be like
[
"0":[
{
"OrderNo": "1",
"partycode": "10",
"OrderDetails": [
{
"Item": "abc",
"price": 250
},
{
"Item": "xyz",
"price": 250
}
]
}
],
"1":[
{
"OrderNo": "2",
"partycode": "20",
"OrderDetails": [
{
"Item": "pqr",
"price": 250
},
{
"Item": "lmn",
"price": 250
}
]
}
]
]
This is What i Tried
$mainarray = array();
$orderarray = array();
$orderitemarray = array();
if (count(combinedarray) > 0) {
foreach (combinedarray as $obj) {
$orderarray[] = array("orderid" => $obj->orderid);
$orderitemarray[] = array("Item" => $obj->Item, "price" => $obj->price);
}
}
$mainarray[] = array_unique($orderarray);
$mainarray['OrderDetails'] = $orderitemarray;
echo json_encode($mainarray);
$mainarray = array();
foreach ($combinedarray as $x) {
$id = $x['orderid'];
unset($x['orderid']);
if (! isset($mainarray[$id])) {
$mainarray[$id]['OrderNo'] = $id;
}
$mainarray[$id]["OrderDetails"][] = $x;
}
// Now $mainarray has indexes equal to OrderNo. To count it from zero, use array_values
echo json_encode(array_values($mainarray), JSON_PRETTY_PRINT);
demo
By your given array
$combinedarray[]=array('orderid'=>1,'partycode'=>10,"item"=>'abc',"price"=>250);
$combinedarray[]=array('orderid'=>1,'partycode'=>10,"item"=>'xyz',"price"=>250);
$combinedarray[]=array('orderid'=>2,'partycode'=>20,"item"=>'pqr',"price"=>250);
$combinedarray[]=array('orderid'=>2,'partycode'=>20,"item"=>'lmn',"price"=>250);
Here is my solution for this
$new = array();
foreach($combinedarray as $r){
$new[$r['orderid']]['orderid'] = $r['orderid'];
$new[$r['orderid']]['partycode'] = $r['partycode'];
$new[$r['orderid']][] = array("item"=>$r['item'],"price"=>$r['price']);
}
$json = json_encode($new);
echo '<pre>';print_r($new);
echo $json;

json get largest number

I get this JSON after running query of particular customer sale history.
$output=
[
{
"customerID": 52970,
"sale": [
{
"item": "pencil",
}
],
"saleNumber": "25",
},
{
"customerID": 52970,
"sale": [
{
"item": "book",
}
],
"saleNumber": "26",
},
{
"customerID": 52970,
"sale": [
{
"item": "pen",
}
],
"saleNumber": "27",
}
]
when it comes to retrieving data such as customerID, I json decode($obj = json_decode($output)) and get the customerID as $ID = $obj->{'customerID'};
How to get the maximum saleNumber from this JSON
You could simply loop through the JSON and compare it. E.g.
$max = 0;
for($i = 0; $i < count($obj); $i++)
{
if((int)$obj[$i]->{"saleNumber"} > (int)$max)
$max = (int)$obj[$i]->{"saleNumber"};
}
// The max value should be in $max
EDIT
Also if saleNumber is the last element in the object, you shouldn't have a ','

Merge results of single JSON output with PHP

I have a JSON array as per below:
{
"aaData": [
{
"Date_time": "23",
"traffic": "22",
"direction": "sent"
},
{
"Date_time": "24",
"traffic": "55",
"direction": "sent"
},
{
"Date_time": "25",
"traffic": "60",
"direction": "sent"
},
{
"Date_time": "26",
"traffic": "43",
"direction": "sent"
},
{
"Date_time": "27",
"traffic": "50",
"direction": "sent"
},
{
"Date_time": "23",
"traffic": "50",
"direction": "received"
},
{
"Date_time": "24",
"traffic": "42",
"direction": "received"
},
{
"Date_time": "25",
"traffic": "52",
"direction": "received"
},
{
"Date_time": "26",
"traffic": "47",
"direction": "received"
},
{
"Date_time": "27",
"traffic": "36",
"direction": "received"
}
]
}
What I'd like to do with it is combine all the results with the same date into a single entry - so for date_time 23 I want it to appear like this
"Date_time": "23",
"traffic-sent": "22",
"traffic-received": "50"
I'd like to do this with PHP if possible? The data is coming from two separate mySQL queries, coming from to different mySQL databases. I've tried combining the output of the query to do what I need (tried Joins and Unions) but can't get past the separation of the results as per my first example.
The part of the SQL query creating the JSON looks like this:
while($row = mysqli_fetch_assoc($result)) {
$model[$i]['Date_time'] = $row['the_day'];
$model[$i]['traffic'] = $row['traffic'];
$model[$i]['direction'] = $row['TABLE_NAME'];
$i++;
}
And the SQL looks like this:
(SELECT
DAY(`Time`) AS the_day,
count(accounts.accName) AS traffic,
"sent" AS TABLE_NAME
FROM
bss.ss_sent LEFT JOIN bss.accounts ON ss_sent.Customer = accounts.accName
WHERE
YEARWEEK(`Time`) = YEARWEEK(CURRENT_DATE)
AND
Customer != " "
AND
accShortName = "QRR"
GROUP BY
the_day)
UNION
(SELECT
DAY(Date_time) AS the_day,
count(AS_Task) AS traffic,
"received" AS TABLE_NAME
FROM
im_stats.as_counter
WHERE
AS_Task = "QRR3 Incoming"
AND
YEARWEEK(Date_time) = YEARWEEK(CURRENT_DATE)
GROUP BY
the_day
Order by the_day)
IF anyone can advise of a way to combine the results I'd very much appreciate it.
UPDATE:
This is how I've entered Populus's code:
$i = 0;
while($row = mysqli_fetch_assoc($result)) {
$model[$i]['Date_time'] = $row['the_day'];
$model[$i]['traffic'] = $row['traffic'];
$model[$i]['direction'] = $row['TABLE_NAME'];
$i++;
}
$combined = array();
foreach ($model as $val) {
$date_time = $val['Date_time'];
if (!isset($combined[$date_time)) {
$combined[$date_time] = array(
'Date_time' => $date_time,
'traffic_sent' => 0,
'traffic_received' => 0,
);
}
if ('received' == $val['direction']) {
$combined[$date_time]['traffic_received'] += $val['traffic'];
} else {
$combined[$date_time]['traffic_sent'] += $val['traffic'];
}
}
header('Content-type: application/json');
print json_encode(array('aaData' => $combined), JSON_PRETTY_PRINT);
This could probably be done using SQL (which you haven't provided), but if you really want PHP:
$combined = array();
foreach ($model as $val) {
$date_time = $val['Date_time'];
if (!isset($combined[$date_time])) {
$combined[$date_time] = array(
'Date_time' => $date_time,
'traffic_sent' => 0,
'traffic_received' => 0,
);
}
if ('received' == $val['direction']) {
$combined[$date_time]['traffic_received'] += $val['traffic'];
} else {
$combined[$date_time]['traffic_sent'] += $val['traffic'];
}
}
Your desired array is now in $combined. If you don't want the keys, you can remove it:
$result = array_values($combined);
Try it this way:
while($row = mysqli_fetch_assoc($result)) {
if ($row['direction'] == 'sent')
$dt[$row['Date_time']]['traffic-sent'] += $row['traffic'];
elseif ($row['direction'] == 'recieved')
$dt[$row['Date_time']]['traffic-recieved'] += $row['traffic'];
}
foreach ($dt as $date) {
echo "Date_time: " . key($date) . ",<br/>" .
"traffic_sent: " . $date['traffic-sent'] . ",<br/>" .
"traffic-recieved: " . $date['traffic-recieved'] . "<br/><br/>";
}

PHP Array to JSON

I'm trying to build a JSON object from a mysql query. The JSON structure that I'm striving for should look like this:
{
"a": [
{
"user": "alb",
"time": "2011-09-12 05:56:36"
},
{
"user": "arg",
"time": "2011-09-12 05:56:36"
}
]
"b": [
{
"user": "blah",
"time": "2011-09-12 05:56:36"
},
{
"user": "bleh",
"time": "2011-09-12 05:56:36"
}
]
}
However, my code always returns a JSON object wrapped in an array like so:
[
{
"a": [
{
"user": "alb",
"time": "2011-09-12 05:56:36"
},
{
"user": "arg",
"time": "2011-09-12 05:56:36"
}
]
"b": [
{
"user": "blah",
"time": "2011-09-12 05:56:36"
},
{
"user": "bleh",
"time": "2011-09-12 05:56:36"
}
]
}
]
Here is the php code I'm using:
<?php
$json_data = array();
foreach($blogs as $blog)
{
$sql = "SELECT * from users";
$query = mysql_query($sql);
$ablog = array();
while ($row = mysql_fetch_assoc($query))
{
$json_element = array(
"user"=> $row[username] ,
"time"=> $row[time]
);
array_push($ablog,$json_element);
}
$eblog = array($blog => $ablog);
array_push($json_data,$eblog);
}
$json_output = json_encode($json_data);
print $json_output;
?>
I was wondering: Why am I getting a JSON object wrapped in an array? What am I doing incorrectly in the code above?
Thank you.
The following two lines are creating one-element associative arrays and appending the one-element array to your larger $json_data array:
$eblog = array($blog => $ablog);
array_push($json_data,$eblog);
Instead, just add a new key/value pair to your original array:
$json_data[$blog] = $ablog;

Categories