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
Related
I am trying to remap an response from a query to the database and group like items in one array. for example, from this example below.
Response:
[
"Location"=> "City 1",
"AptDate"=> "2020-09-16",
"AptTime"=> "11:00",
"AptLength"=> "45",
"AptStatus"=> "1",
"Operatory"=> "1 RECALL",
"OperatoryNum"=> "2"
],
[
"Location"=> "City 2",
"AptDate"=> "2020-09-16",
"AptTime"=> "09:00",
"AptLength"=> "45",
"AptStatus"=> "1",
"Operatory"=> "1 RECALL",
"OperatoryNum"=> "2"
],
[
"Location"=> "City 1",
"AptDate"=> "2020-09-16",
"AptTime"=> "12:00",
"AptLength"-> "45",
"AptStatus"=>"1",
"Operatory"=> "1 RECALL",
"OperatoryNum"=> "2"
[,
looping through results:
$remappedData=[];
foreach ($result as $value)
{
$remappedData[] = [
'location' => $value['Location'],
// And so on
];
}
}
This doesnt really give me what i need as I am trying to group the array based on Location and add the AppDate base on that location. Something like this.
{
"Location": "City 1",
"AptDate": ["2020-09-16","2020-09-16"],
"AptTime": ["11:00","12:00"],
"AptLength": ["45","45"],
"AptStatus": ["1","1"],
"Operatory": ["1 RECALL","1 RECALL"],
"OperatoryNum": ["2","2"]
},
{
"Location": "City 2",
"AptDate": ["2020-09-16"],
"AptTime": ["09:00"],
"AptLength":[ "45"],
"AptStatus": ["1"],
"Operatory": ["1 RECALL"],
"OperatoryNum": "2"
},
So based on your scenario, you want grouping on Location and group all other attributes by keeping them in array.
foreach ($result as $value)
{
$remappedData[$value['Location']]['location'] = $value['Location'];
$remappedData[$value['Location']]['AptDate'][] = $value['AptDate']; // Notice we're creating an array here.
$remappedData[$value['Location']]['AptTime'][] = $value['AptTime'];
// so on all other attributes which needs to be grouped.
}
Note: Here we've created index as Location. If we don't want Location as key, we want as array(may be for frontend) use below code.
$temp = [];
$remappedData=[];
$intCurrentIndex = -1;
foreach ($result as $value)
{
if(isset($temp[$value['Location']])){
$oldIndex = $temp[$value['Location']];
$remappedData[$oldIndex]['AptDate'][] = $value['AptDate'];
$remappedData[$oldIndex]['AptTime'][] = $value['AptTime'];
}
else{
$temp[$value['Location']] = ++$intCurrentIndex;
$remappedData[$intCurrentIndex]['location'] = $value['Location'];
$remappedData[$intCurrentIndex]['AptDate'][] = $value['AptDate'];
$remappedData[$intCurrentIndex]['AptTime'][] = $value['AptTime'];
}
}
When Exporting database to json I get it in this form:
[
{
"id": "1",
"siteId": "1",
"siteUrl": "localhost",
"identity": "mobie",
"lastIp": "127.0.0.1",
"lastLogin": "2018-05-17",
"loginCountry": "GB",
}
]
Warning: Illegal string offset 'id' in C:\xamppp\htdocs\auth\mysql.php on line 81
To all of the $user variables.
My database structure is shown as above in the first json output.
Code
public function db2json($query){
$stmt = $this->db->prepare($query);
$stmt->execute();
$data=$stmt->fetch(PDO::FETCH_ASSOC);
$output = [];
foreach ( $data as $result ) { // Change this to loop over the data
$user = [];
$user["id"] = $result["id"];
$user["siteId"] = $result["siteId"];
$user["lastIp"] = $result["lastIp"];
$user["lastLogin"] = $result["lastLogin"];
$user["loginCountry"] = $result["loginCountry"];
$output[$result["siteUrl"]][$result["identity"]] = $user;
}
echo json_encode($output, JSON_PRETTY_PRINT);
}
I have had to build up some test data, but this will just mean that you change the foreach() to loop over your database result instead. Rather than just assigning the result straight to the output, this just creates the various arrays as you want them in the output...
$output = [];
foreach ( $data as $result ) { // Change this to loop over the data
$user = [];
$user["id"] = $result["id"];
$user["siteId"] = $result["siteId"];
$user["lastIp"] = $result["lastIp"];
$user["lastLogin"] = $result["lastLogin"];
$user["loginCountry"] = $result["loginCountry"];
$output[$result["siteUrl"]][$result["identity"]] = $user;
}
echo json_encode($output, JSON_PRETTY_PRINT);
With my test data, this outputs...
{
"localhost": {
"mobie": {
"id": "1",
"siteId": "1",
"lastIp": "127.0.0.1",
"lastLogin": "2018-05-17",
"loginCountry": "GB"
},
"user2": {
"id": "1",
"siteId": "1",
"lastIp": "127.0.0.1",
"lastLogin": "2018-05-17",
"loginCountry": "GB"
}
},
"othersite": {
"user1": {
"id": "1",
"siteId": "1",
"lastIp": "127.0.0.1",
"lastLogin": "2018-05-17",
"loginCountry": "GB"
}
}
}
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);
I am using slimphp v2 and I have the following function
function gt($user) {
$sql = "select id, id as categoryId, mobile, task from actions where status=0";
try {
$db = newDB($user);
$stmt = $db - > prepare($sql);
$stmt - > execute();
$gs = $stmt - > fetchAll(PDO::FETCH_OBJ);
if ($gs) {
$db = null;
echo json_encode($gs, JSON_UNESCAPED_UNICODE);
} else {
echo "Not Found";
}
} catch (PDOException $e) {
echo '{"error":{"text":'.$e - > getMessage().
'}}';
}
}
The default json output looks like:
[{
"id": "1",
"categoryId": "1",
"mobile": "111",
"task": "test"
},
{
"id": "2",
"categoryId": "2",
"mobile": "222",
"task": "test2"
}]
and the output that i am trying to make. I need to generate an ID: 1_(id) then format it like this
[{
id: "1",
task: "test",
}, {
ID: "1_1", //generate this, add 1_id
categoryId: "1",
mobile: "00000",
}, {
id: "2",
task: "test2",
}, {
ID: "1_2", //generate this, add 1_id
categoryId: "2",
mobile: "11111"
}];
Is it possible?
Thanks
I'm not sure if this is exactly what your after but you can gain the desired JSON output by converting your original JSON into an associative array and then restructure the data on each iteration using a Foreach() loop into a new assoc array. After that, you can just convert it back to JSON using json_encode().
Code:
$json = '[{
"id": "1",
"categoryId": "1",
"mobile": "111",
"task": "test"
},
{
"id": "2",
"categoryId": "2",
"mobile": "222",
"task": "test2"
}]';
$jsonArr = json_decode($json, TRUE);
$newArr = [];
foreach ($jsonArr as $v) {
$newArr[] = ['id:'=>$v['id'], 'task:' => $v['task']];
$newArr[] = ['ID:'=>'1_' . $v['id'], 'categoryId' => $v['categoryId'], 'mobile'=>$v['mobile']];
}
$newJson = json_encode($newArr);
var_dump($newJson);
Output:
[{
"id:": "1",
"task:": "test"
}, {
"ID:": "1_1",
"categoryId": "1",
"mobile": "111"
}, {
"id:": "2",
"task:": "test2"
}, {
"ID:": "1_2",
"categoryId": "2",
"mobile": "222"
}]
Edit -- Updated Answer
As discussed in comments, your outputting your SQL array as an object. I've set the Fetch to output as an associative array using PDO::FETCH_ASSOC and changed the foreach() loop to reference the assoc array $gs. This should work but if not then output your results for $gs again using var_dump($gs). You will still need to encode to JSON if needed but this line has been commented out.
function gt($user) {
$sql = "select id, id as categoryId, mobile, task from actions where status=0";
try {
$db = newDB($user);
$stmt = $db->prepare($sql);
$stmt->execute();
$gs = $stmt->fetchAll(PDO::FETCH_ASSOC); //Fetch as Associative Array
if ($gs) {
$db = null;
$newArr = [];
foreach ($gs as $v) { //$gs Array should still work with foreach loop
$newArr[] = ['id:'=>$v['id'], 'task:' => $v['task']];
$newArr[] = ['ID:'=>'1_' . $v['id'], 'categoryId' => $v['categoryId'], 'mobile'=>$v['mobile']];
}
//$newJson = json_encode($newArr); //JSON encode here if you want it converted to JSON.
} else {
echo "Not Found";
}
} catch(PDOException $e) {
//error_log($e->getMessage(), 3, '/var/tmp/php.log');
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}
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;