Mapping SQL query results to JSON in PHP - php

I'm running into some issues getting the correct JSON output from my SQL query. Essentially what I'm struggling with is getting an array of options objects as opposed to singular option objects.
$query = 'SELECT matchup.matchupID, matchup_option.player_name, matchup_option.player_id FROM matchup
INNER JOIN matchup_option
ON matchup_option.matchupID= matchup.matchupID;';
$attachments = $db->query($query);
$data = array();
while ($attachment = $db->fetch_array($attachments)){
$data[] = array (
'id' => $attachment['matchupID'],
'options' => array(
array (
"name" => $attachment['player_name'],
"playerid" => $attachment['player_id']
)
)
);
//VAR_DUMP($attachment);
}
$data = array("matchup"=>$data);
print json_encode($data);
Gives me this output:
{
"matchup":[
{
"id":"111222",
"options":[
{
"name":"111",
"playerid":"111"
}
]
},
{
"id":"111222",
"options":[
{
"name":"222",
"playerid":"222"
}
]
}
]
}
And here's what I'm trying to get to:
{
"matchup":[
{
"id":"111222",
"options":[
{
"name":"111",
"playerid":"111"
},
{
"name":"222",
"playerid":"222"
}
]
}
]
}
I'd like to follow best practices as well as structure this appropriately, if there's a better way to go about this, please let me know!

You need to store $attachment['matchupID'] as an array key of $data:
$data = array();
while ($attachment = $db->fetch_array($attachments)){
if (!isset($data[$attachment['matchupID']])) {
$data[$attachment['matchupID']] = array (
'id' => $attachment['matchupID'],
'options' => array()
);
}
$data[$attachment['matchupID']]['options'][] = array (
"name" => $attachment['player_name'],
"playerid" => $attachment['player_id']
);
}
// use `array_values` to reindex `$data`
$data = array("matchup" => array_values($data));
print json_encode($data);

Related

json encode missing the comma?

I'm trying to get the correct json output after using php nested array and somehow when I use the json_encode it misses the commas between each key value pair and array of item.
$don_info_arr = array();
$don_info_arr['don_info']= array();
$st_contacts_arr = array();
$st_contacts_arr['st_contacts']= array();
$don_contact_arr = array();
$don_contact_arr['don_contact']= array();
$don_contact_item =array(
'first_name' => $donor->first_name,
'last_name' => $donor->last_name
);
//correspondence_contact
$correspondence_contact_arr = array();
$correspondence_contact_arr['correspondence_contact']= array();
$correspondence_contact_item =array(
'first_name' => $donor->first_name_c,
'last_name' => $donor->last_name_c
);
$submission = array(
"don_info" => array (
"st_contacts" => array (
"don_contact" => $don_contact_item,
"correspondence_contact" =>$correspondence_contact_item)
)));
echo json_encode($submission);
getting this result now.
{
"don_info": {
"st_contacts": {
"don_contact": {
"first_name": "Test1"
"last_name": "Test1"
}
"correspondence_contact": {
"first_name": "ABC"
"last_name": "ACDD"
}
}
}
What I want:
{
"don_info":{
"st_contacts":{
"don_contact":{
"first_name":"Test1",
"last_name":"Test2"
},
"correspondence_contact":{
"first_name":"ABC",
"last_name":"ACDD"
}
}
}

How to create nested tag in JSON

I have been fiddling with JSON nested tag, tried the basics now I want to go a little further, but it has been giving a little head ache to me. I have this public function below
public function returnResponse($code, $data){
header("content-type: application/json");
$result = json_encode(['response' => ['status' => $code, "message" => $data]]);
echo $result ; exit;
}
$order= $cust->getDeliveryDetail();
USING print_r($order);
Array
(
[0] => Array
(
[0] => Array
(
[order_id] => 4444
[menu] => two
[order_uniq] => 999oeo4
)
)
[1] => Array
(
[0] => Array
(
[pro_name] => Beans
[pro_sub] => Goods
[pro_type] => Open CA
)
[1] => Array
(
[pro_name] => Rice
[pro_sub] => Fiber
[pro_type] => Diverca
)
)
)
then attaching object with elements and value which references
$result ['order_id'] = $order[0][0]['order_id'];
$result ['menu'] = $order[0][0]['menu'];
$result ['order_uniq'] = $order[0][0]['order_uniq'];
$result ['pro_name'] = $order[0][0]['pro_name'];
$result ['pro_sub'] = $order[0][0]['pro_sub'];
$result ['pro_type'] = $order[0][0]['pro_type'];
$this->returnResponse(SUCCESS_RESPONSE, $result); //THIS IS THE ORIGINAL BEGINNING PUBLIC FUNCTION WE CREATED
to create this JSON nested tag below
{
"response": {
"status": 200,
"message": {
"order_id": "4444",
"menu": "two",
"order_uniq": "999oeo4",
"pro_name": "Beans",
"pro_sub": "Goods",
"pro_type": "Openca",
}
}
}
but I want to create a JSON nested tag like this below
{
"response": {
"status": 200,
"message": {
"order_id": "4444",
"menu": "two",
"order_uniq": "999oeo4",
"items": [
{
"pro_name": "Beans",
"pro_sub": "Goods",
"pro_type": "Openca",
}
{
"pro_name": "Rice",
"pro_sub": "Fiber",
"pro_type": "Diverca",
}
]
},
}
}
If it helps -- maybe not, the right way to do this in the beginning would be to create an OrderItems table/dictionary. Then store items in that table referrencing your Order table with "order_id". That way you could pull order_items as one array object, and convert that to json really simply.
Here since, you are getting "pro_name", "pro_sub" & "pro_type" as items, you would programmatically pull those out and create your own order_items array.
$order= $cust->getDeliveryDetail();
$order_id = $order[0][0]['order_id'];
$order_menu = $order[0][0]['menu'];
$order_uniq = $order[0][0]['order_uniq'];
$items = [];
foreach($order[1] as $order_item) {
$items[] = $order_item;
}
$result = [];
$result["order_id"] = $order_id;
$result["menu"] = $order_menu;
$result["order_uniq"] = $order_uniq;
$result["order_items"] = $items;
$this->returnResponse(SUCCESS_RESPONSE, $result);
Like this?
$result = array(
'order_id' = > $order[0][0]['order_id'],
'menu' => $order[0][0]['menu'],
'order_uniq' => $order[0][0]['order_uniq'],
'pro_name' => $order[0][0]['pro_name'],
'pro_sub' => $order[0][0]['pro_sub'],
'pro_type' => $order[0][0]['pro_type'],
'items' => array()
);
foreach($order[1] as $item) {
array_push(
$result['items'],
array(
'pro_name' => $item['pro_name'],
'pro_sub' => $item['pro_sub'],
'pro_type' => $item['pro_type'],
)
);
}

Codeigniter - Inserting data into MySQL where only one of the Input values is an array

I am learning Codeigniter and hitting some turbulence. One of my input fields collects an array of values (from check-boxes), while the rest are single values. I would like to insert the data into MySQLi in such a way that the number of inserted rows is equal to the number of values in the array. It looks like:
My Controller:
function request_rooms() {
if ($_POST) {
//room is an array or one or more values
$this->form_validation->set_rules('room[]', 'Select Box', 'trim|required|min_length[1]|max_length[25]');
$this->form_validation->set_rules('guest_id', 'Guest ID', 'trim|required|xss_clean|min_length[4]|max_length[20]');
$this->form_validation->set_rules('date_in', 'Check-in Date', 'trim|required|exact_length[10]');
$this->form_validation->set_rules('date_out', 'Check-out Date', 'trim|required|exact_length[10]');
if ($this->form_validation->run($this) == FALSE) {
$somedata = array('errors' => validation_errors());
$this->session->set_flashdata($somedata);
require("includes/load_view_reservation.php");
} else {
//Prepare data to send to Reservation model
$data = array(
'room_no' = ?
'guest_id' = $this->input->post('guest_id'),
'check_in' = $this->input->post('check_in'),
'check_in' = $this->input->post('check_in')
$this->reservation_model->insert_reservation($data);
}
}
}
The Problem:
My problem is how to handle the room array. I want to create a $data array for the data to be inserted into the Database. So suppose the room array input ($this->input->post('room[]')) is as follows:
$room = array(42, 123, 16);
I would like the $data array to be like:
$data = array
(
array(
"room_no" => "42",
"guest_id" => "2",
"date_in" => "2018-05-20",
"date_out" => "2018-05-27"
),
array(
"room_no" => "123",
"guest_id" => "2",
"date_in" => "2018-05-20",
"date_out" => "2018-05-27" ),
array(
"room_no" => "16",
"guest_id" => "2",
"date_in" => "2018-05-20",
"date_out" => "2018-05-27" )
);
I have a faint idea that a loop could accomplish something like this so that the room_no part of the array has each of the values from the array while the other values remain the same, but I can't see how to proceed.
Question:
How do I create a Multidimensional array like above in Codeigniter? Secondly, This far, I have only inserted (into MySQL) a simple one-dimensional array using a Codeigniter Model. How do I insert a Multidimensional array like the one above? Please help.
Hope this will help you :
First method insert individual record;
//$rooms = $this->input->post('room');
$rooms = array(42, 123, 16);
if ( ! empty($rooms))
{
foreach($rooms AS $room)
{
$data['room_no'] = $room;
$data['guest_id'] = $this->input->post('guest_id');
$data['check_in'] = $this->input->post('check_in');
$this->reservation_model->insert_reservation($data);
}
}
Your model method insert_reservation should be like this :
public function insert_reservation($data)
{
return $this->db->insert('table_name',$data);
}
Second method insert multiple (batch) record;
//$rooms = $this->input->post('room');
$rooms = array(42, 123, 16);
if( ! empty($rooms))
{
foreach($rooms AS $room)
{
$data[] = [
'room_no' => $room,
'guest_id' => $this->input->post('guest_id'),
'check_in' => $this->input->post('check_in'),
];
}
}
//print_r($data);
$this->reservation_model->insert_reservation($data);
In this case your model method insert_reservation should be like this :
public function insert_reservation($data)
{
return $this->db->insert_batch('table_name',$data);
}
For more : https://www.codeigniter.com/user_guide/database/query_builder.html#inserting-data
doesn't look that tough just iterate over your array
something like the following should do the job.
$room = array(42, 123, 16);
$arrData = [];
foreach($room AS $roomNo)
{
$arrData[] = [
'room_no' => $roomNo,
'guest_id' => $this->input->post('guest_id'),
'check_in' = $this->input->post('check_in'),
'check_in' = $this->input->post('check_in')
];
}
print_r($arrData);

convert stdclass object array to json correct

Sorry for my English, I need help I want to convert a query which will return this.
{"ids":"1","user":"aki","last":"terris","job":"programmer"}{"ids":"1","user":"ako","last":"acros","job":"Artist"}
Change it to
{
"users": [
{
"user": "aki",
"last": "terris",
"job": "programmer"
},
{
"user": "ako",
"last": "acros",
"job": "Artist"
}
]
}
I tried with while, foreach but none gives me a valid format, some help
consult:
$sql = $db->query("SELECT * FROM user_s WHERE ids = '1' ");
$set_users = $sql;
Ex :
$entity = array();
while ($get_users = $set_users->fetch_object()) {
$entity = array(
'id' => $get_users->id,
'user' => $get_users->user
);
}
$fsi = array(
'users' => $entity,
);
echo $fsi;
Try this:
$results = new \stdClass;
$results->users = [];
while ($get_users = $set_users->fetch_object()) {
$entity = array(
'user' => $get_users->user,
'last' => $get_users->last,
'job' => $get_users->job,
);
$results->users[] = $entity;
}
echo json_encode($results);
You can use fetch_all with the MYSQLI_ASSOC option, to get data immediately in the desired format, i.e. as an associative array which will render JSON object notation when converted with json_encode:
$fsi = [ 'users' => $set_users->fetch_all(MYSQLI_ASSOC) ];
echo json_encode($fsi);
Make sure to use an SQL query that only selects the fields that you want to end up in the JSON.

How to format array as key : value?

I have a array like this:
Array
(
[0] => Chat Show
[1] => Non-fiction
[2] => Inspirational
)
And i am trying to get this format:
"genres": [
{
"name": "Chat Show"
},
{
"name": "Non-fiction"
},
{
"name": "Inspirational"
}
]
but i get something like this:
genres": [
"Chat Show",
"Non-fiction",
"Inspirational"
]
This is what i am doing:
while($row = mysqli_fetch_array($Data))
{
$Genres = explode('/', filter_var(rtrim($row['genres'], '/'), FILTER_SANITIZE_URL));
}
and then this is part of a bigger array
"genres" => $Genres
print_r(
json_encode(["genres" => array_map(
function($v) { return ['name' => $v]; },
$Genres)]));
result
{"genres":[{"name":"Chat Show"},{"name":"Non-fiction"},{"name":"Inspirational"}]}
For example, here is your array in PHP
$var = array(
"Chat Show",
"Non-fiction" ,
"Inspirational"
);
Without a key "name". You should create a new array and push each element as an array to your new array.
$result = array();
foreach($var as $name)
{
$arr = array("name"=>$name);
array_push($result, $arr);
}
after that, encode your $result by using json_encode
$json = json_encode($result,true);
echo $json;
Here is my output by echo $json.
[{"name":"Chat Show"},{"name":"Non-fiction"},{"name":"Inspirational"}]
Try this:
$Genres=array("Chat Show","Non-fiction","Non-fiction");
$new["genres"]=array();
foreach($Genres as $key => $name){
$new["genres"][$key] = ['name' => $name];
}
echo json_encode($new);
Output
{"genres":[{"name":"Chat Show"},{"name":"Non-fiction"},{"name":"Non-fiction"}]}
The json string you posted here is not a valid json OR is part of json.
So, you might already have genres in your javascript, and want to get the remaining thing, which is
[
{ "name": "Chat Show" },
{ "name": "Non-fiction" },
{ "name": "Inspirational" }
]
Your current PHP $Genres looks like this because you are exploding the string
$Genres = [ 'Chat Show', 'Non-fiction', 'Inspirational' ];
Apply this to change values of your current $Genres
array_walk($Genres, function(&$v){ $v = ['name'=>$v]; });
Use it in your javascript like,
"genres": <?php json_encode($Genres)?>
Try this:
$genres_new['name']=$Genres;
echo json_encode($genres_new);
Your problem is, that you have simple array of strings, but you want an associative multilevel array. This is an relative simple operation. First lets illustrate the problem with some code:
// That is what you have, an :
$Genres = [
"Chat Show",
"Non-fiction",
"Inspirational",
];
// or the same for php > 5.4:
$Genres = array(
"Chat Show",
"Non-fiction",
"Inspirational",
);
This will produce the following json string (echo json_encode($Genres);):
["Chat Show","Non-fiction","Inspirational"]
But if you want such an output:
[{"name":"Chat Show"},{"name":"Non-fiction"},{"name":"Inspirational"}]
You have to convert the strings into an array. You can do that with that (or a similar loop):
foreach($Genres as $key => $name){
$Genres[$key] = ['name' => $name];
}
After that your array look like this:
Array (
0 =>
array (
'name' => 'Chat Show',
),
1 =>
array (
'name' => 'Non-fiction',
),
2 =>
array (
'name' => 'Inspirational',
),
)
Putting things together you will get something like that:
<?php
// Do whatever is necessary to build your Genres array ...
$Genres = [
"Chat Show",
"Non-fiction",
"Inspirational",
];
// Convert the array into an array of arrays
foreach($Genres as $key => $name){
$Genres[$key] = ['name' => $name];
}
echo json_encode($Genres);
/**
Now you will get this output:
[{"name":"Chat Show"},{"name":"Non-fiction"},{"name":"Inspirational"}]
*/
// After that you can add it to the bigger array:
$biggerArray = [];
$biggerArray['genres'] = $Genres;
echo json_encode($biggerArray);
/**
Output:
{"genres":[{"name":"Chat Show"},{"name":"Non-fiction"},{"name":"Inspirational"}]}
*/

Categories