parse and fetch data in flutter - arrays

I found a code that works well. I want to use it in a project but I can't. I think the problem is at the level of recovery and then their conversion according to the initial project
this is the array in the source code
loadPreviousEvents() {
mySelectedEvents = {
"2022-09-13": [
{"eventDescp": "11", "eventTitle": "111"},
{"eventDescp": "22", "eventTitle": "22"}
],
"2022-09-30": [
{"eventDescp": "22", "eventTitle": "22"}
],
"2022-09-20": [
{"eventTitle": "ss", "eventDescp": "ss"}
]
};
}
here is how I tried to do the same by retrieving the data in my database
void getData() async {
var url = 'http://xxxxxxxxx/getEvents.php';
var res = await http.get(Uri.parse(url));
var response = json.decode(res.body);
var mySelectedEvents =
groupBy(response, (Map obj) => obj['date']).map((k, v) => MapEntry(
k,
v.map((item) {
item.remove('date');
return item;
}).toList()));
print(mySelectedEvents);
}
List _listOfDayEvents(DateTime dateTime) {
if (mySelectedEvents[DateFormat('yyyy-MM-dd').format(dateTime)] != null) {
return mySelectedEvents[DateFormat('yyyy-MM-dd').format(dateTime)]!;
} else {
return [];
}
}
here are my 2 tables
INSERT INTO `event_date` (`id`, `date`, `selectdate`) VALUES
(4, '2022-09-17', '2022-09-17 22:13:04.508644'),
(5, '2022-09-17', '2022-09-17 23:19:05.885897'),
(6, '2022-09-17', '2022-09-17 23:19:05.885897'),
(7, '2022-09-20', '2022-09-20 00:00:00.000Z'),
(8, '2022-09-17', '2022-09-17 23:20:46.357121');
INSERT INTO `event_list` (`id`, `descript`, `title`, `id_event_date`) VALUES
(1, '11', '111', 1),
(2, '22', '22', 1),
(3, '22', '22', 2),
(4, 'ss', 'ss', 3);
this ma PHP code
$table = "event_date";
$table2 = "event_list";
$db_data = array();
$sql = "SELECT *
FROM $table D
,$table2 E
WHERE D.id = E.id_event_date
";
$result = $conn->query($sql);
if($result->num_rows >0){
while($rows = $result->fetch_assoc()){
$db_data[] = $rows;
}//fin while
//Retourn toutes les reponses en json
echo json_encode(utf8ize($db_data));
}else{
echo "erreur";
}

Related

How to recursively create a Modal with an array of data in Swift

I need to recursively add these comments in the correct order.
Currently i get an array of comments that are unsorted.
These comments can be the top level or can be a child of the top level.
I was using this recursive method to add them but i can’t seem to get it right.
The result should be an array of CommentModal’s [CommentModal]
For reference:
The postID is the topLevel comment that the child belongs to. Every child comment will have a postID so that they know where they belong to. If the child has a child, the top level child’s commentID will be the child’s postID.
Data and Data Models
struct Comment {
var postID: String
var commentID: String
var date: Double
}
class CommentModal {
var mainComment: Comment
var childComment: [CommentModal] = []
init(mainComment: Comment) {
self.mainComment = mainComment
}
}
let data: [Comment] = [
Comment(postID: "RootPostID", commentID: "116", date: 1),
Comment(postID: "RootPostID", commentID: "117", date: 2),
Comment(postID: "RootPostID", commentID: "118", date: 3),
Comment(postID: "116", commentID: "216", date: 4),
Comment(postID: "117", commentID: "217", date: 5),
Comment(postID: "118", commentID: "218", date: 6),
Comment(postID: "216", commentID: "316", date: 7),
Comment(postID: "216", commentID: "317", date: 8),
]
Initialized
private func index(comments: [Comment]) {
discardableCachedComments = comments
commentModalArray = addChildren(from: comments)
}
private func addChildren(from comments: [Comment]) -> [CommentModal] {
var result: [CommentModal] = []
for comment in comments {
let children = discardableCachedComments.filter { $0.postID == comment.commentID }
discardableCachedComments.removeAll { $0.postID == comment.commentID }
let commentModal = CommentModal(mainComment: comment)
if children.count >= 1 {
commentModal.childComment = addChildren(from: children)
}
discardableCachedComments.removeAll { $0.commentID == comment.commentID }
result.append(commentModal)
}
return result
}
Desired Output
Using the data above i want to see the result be:
An array of 3 Top Level CommentModals.
Each of those Top Level CommentModals will have a childComment which is an array of CommentModal. For one of those childComment we will also see it have two values in childComment.
If you see the data you will see how the postID and commentID are assembled so that they are added correctly in its respective modal.
I've changed a couple of names to make things semantically a little easier to understand, but this should show the gist of it. I've also changed CommentModal into a struct, since that made initialization easier, but you could change it back.
This should be copy/pastable into a Playground:
struct Comment : Codable {
var parentID: String
var id: String
var date: Double
}
struct CommentModel : Codable {
var comment: Comment
var children: [CommentModel] = []
}
let data: [Comment] = [
Comment(parentID: "RootPostID", id: "116", date: 1),
Comment(parentID: "RootPostID", id: "117", date: 2),
Comment(parentID: "RootPostID", id: "118", date: 3),
Comment(parentID: "116", id: "216", date: 4),
Comment(parentID: "117", id: "217", date: 5),
Comment(parentID: "118", id: "218", date: 6),
Comment(parentID: "216", id: "316", date: 7),
Comment(parentID: "216", id: "317", date: 8),
]
func createCommentModels(rootKey: String, input: [Comment]) -> [CommentModel] {
return input
.filter { $0.parentID == rootKey }
.map { comment in
return CommentModel(comment: comment,
children: createCommentModels(rootKey: comment.id,
input: input
))
}
}
func printModal(_ input: CommentModel, indent: Int = 0) {
let indentChars = Array(repeating: " ", count: indent).joined(separator: "")
print("\(indentChars)", input.comment.id)
if !input.children.isEmpty {
print("\(indentChars) - Children:")
input.children.forEach { printModal($0, indent: indent + 4)}
}
}
let result = createCommentModels(rootKey: "RootPostID", input: data)
result.forEach {
printModal($0)
}
Which yields:
116
- Children:
216
- Children:
316
317
117
- Children:
217
118
- Children:
218

Create a dynamic SQL Insert from array object

I have a project in Typescript where I need to create an Insert with all the elements of the object to make only one Insert, instead of one Insert for each array.
This is my current function:
public async insert() {
let object = [{ cod: 'CO',
file: 'CO_SER.csv',
exists: 1},
{ cod: 'ES',
file: 'ES_INS.csv',
exists: 1 } ];
for (let elem of object) {
let insert = `INSERT INTO databaseID VALUES ("${elem.cod}", "${elem.file}", ${elem.exists})`;
}
}
This is what I get:
INSERT INTO databaseID VALUES ("CO", "CO_SER.csv", 1)
INSERT INTO databaseID VALUES ("ES", "ES_INS.csv", 1)
This is what I want to achieve:
INSERT INTO databaseID VALUES ("CO", "CO_SER.csv", 1), ("ES", "ES_INS.csv", 1)
let object = [
{ cod: 'CO',
file: 'CO_SER.csv',
exists: 1},
{ cod: 'ES',
file: 'ES_INS.csv',
exists: 1 } ];
let insert = `INSERT INTO databaseID VALUES ` +
object.map(
elem => `("${elem.cod}", "${elem.file}", ${elem.exists})`
).join(', ')
console.log(insert)

sort an array of objects on multiple key using array-sort

I have a requirement where the array of objects needs to be sorted on certain keys. The keys with which it needs to be sorted is dynamic and it is Not fixed.
I came across array-sort in npm library. Using that, am able to sort on multiple keys but it sorts only on ascending order.
const input = [{id:'1',name:'John',city:'Denver',State:'CO'},
{id:'2',name:'Smith',city:'San Fransisco',State:'CA'},
{id:'3',name:'Adam',city:'Concord',State:'CA'},
{id:'1',name:'John',city:'Concord',State:'CA'}]
I want to sort on State (asc), city (asc) and id (desc). My output should look like
[
{id:'3',name:'Adam',city:'Concord',State:'CA'},
{id:'1',name:'John',city:'Concord',State:'CA'},
{id:'2',name:'Smith',city:'San Fransisco',State:'CA'},
{id:'1',name:'John',city:'Denver',State:'CO'}]
Can anyone please let me know how i can implement sorting on descending using array-sort
Thanks
Maybe you want a JavaScript function like this?
function multicolumnSort(data, orders) {
return data.sort((e1, e2) => {
for (var i = 0; i < orders.length; i++)
if (e1[orders[i].column] != e2[orders[i].column])
return orders[i].desc ^ e2[orders[i].column] < e1[orders[i].column]? 1 : -1;
return 0;
});
}
Then, you may call the function with your order keys:
let orders = [
{
column: 'State'
},
{
column: 'city'
},
{
column: 'id',
desc: true
}
];
let result = multicolumnSort(input, orders);
Check my code
function DESC(i, ii) { // DESC
return (i[key] > ii[key]) ? -1 : ((i[key] < ii[key]) ? 1 : 0);
}
function ASC(i, ii) { // ASC
return (i[key] > ii[key]) ? 1 : ((i[key] < ii[key]) ? -1 : 0);
}
function StartSort(data, myArray, order) {
// data - row for sorting, array - array fo sorting, order - order of sorting
key = data;
arr = myArray;
if (order.toUpperCase() == "ASC") {
sortedArray = arr.sort(ASC);
} else {
sortedArray = arr.sort(DESC);
}
return sortedArray;
}
//sorting started
const input = [{
id: '1',
name: 'John',
city: 'Denver',
State: 'CO'
},
{
id: '2',
name: 'Smith',
city: 'San Fransisco',
State: 'CA'
},
{
id: '3',
name: 'Adam',
city: 'Concord',
State: 'CA'
},
{
id: '1',
name: 'John',
city: 'Concord',
State: 'CA'
}
]
let output1 = StartSort('state', input, 'ASC');
output1 = StartSort('city', output1, 'ASC');
output1 = StartSort('id', output1, 'DESC');
console.log(output1);

Data Changed but front-end did not updated

I have designed a table which will read a object array and a dropdown list for ordering control.
However, when I select other ordering value in dropdown list. The front end table did not update at the same time. It will have a delay, please see the following example.
T0: default select order by "name" -> front end correct(Order by "name")
T1: select order by "age" -> front-end no update (still order by "name")
T2: select order by "name" -> front-end update (order by "age")
T3: select order by "age" -> front-end update (order by "name")
My object array
var data = [
{
key: 1,
name: 'AAA',
age: '10',
},
{
key: 2,
name: 'BBB',
age: '8',
},
{
key: 3,
name: 'name',
age: '12',
},
]
const [listData, setListData] = useState(data);
Drop down control
const handleOrderChange = (value) => {
setOrderValue(value);
};
useEffect(() => {
console.log(orderValue.value); //match what I click
switch (orderValue.value) {
case 'name':
listData.sort((a, b) => (a.name > b.name ? 1 : -1));
break;
case 'age':
listData.sort((a, b) => (a.age> b.age? 1 : -1));
break;
default:
console.log('Default');
}
console.log(listData); //match what I expected
}, [orderValue]);
Front-End
{/* Data */}
{listData.map((item) => (
<DataDetail
key={item.key}
name={item.name}
age={item.age}
></DataDetail>
))}
You should never mutate a state variable as this:
switch (orderValue.value) {
case 'name':
listData.sort((a, b) => (a.name > b.name ? 1 : -1));
break;
case 'age':
listData.sort((a, b) => (a.age> b.age? 1 : -1));
break;
default:
console.log('Default');
}
instead you should use:
useEffect(() => {
switch (orderValue.value) {
case 'name':
const listDataCopy = [...listData]
listDataCopy.sort((a, b) => (a.name > b.name ? 1 : -1));
setListData(listDataCopy)
break;
case 'age':
const listDataCopy = [...listData]
listDataCopy.sort((a, b) => (a.age> b.age? 1 : -1));
setListData(listDataCopy)
break;
default:
console.log('Default');
}
}, [orderValue, listData, setListData]);

How to push an array into json key/value pair of an object i codeigniter array

What am I trying to achieve
So what I was trying to achieve was push an array key/value pair into a JSON object that is in itself an array, so that there is a single object and one of the key-value pairs contains an array.
THIS IS WHAT I AM TRYING TO ACHIEVE as JSON output, another data2 Array inside another data array.
[
{
"data": {
"temp_service_id": "3",
"name": "health checkup",
"price": "10000",
"service_id": "41",
"data2": [
{
"fees": "2000",
"service_name": "Anaesthesiologist"
},
{
"fees": "300",
"service_name": "Andrologist"
},
]
},
}
]
What I have tried
THIS IS MY CONTROLLER :
$where['subtype_id'] = $this->post('org_id');
$where['is_active'] = 'Y';
$table_package_master = 'package_master';
$fetch_package_name = $this->$model_name->fetch($table_package_master,$where);
$array = [];
$array1 = [];
$array2 = [];
if($fetch_package_name){
foreach($fetch_package_name as $row){
$where_r['t1.package_num'] = $row->package_num;
$where_r['t1.is_active'] = 'Y';
$where_r['services.is_active'] = 'Y';
$where_r['t4.is_active'] = 'Y';
$fetch_packages1 = $this->$model_name->fetch_packages1($where_r);
$array['data'] = $fetch_packages1;
$fetch_packages = $this->$model_name->fetch_packages($where_r);
foreach($fetch_packages as $row1){
$where_re['services.service_id'] = $row1->service_id;
$where_re['services.is_active'] = 'Y';
$where_re['template_services.is_active'] = 'Y';
$fetch_package_ser = $this->$model_name->fetch_service_details($where_re);
array_push($array1,$fetch_package_ser);
}
}
$array['data2'] = $array1;
$array3 = [$array];
$this->response($array3);
}
THIS IS MY MODEL :
function fetch($table,$where_con){
$this->db->select('*')->from($table)->where($where_con);
return $this->db->get()->result();
}
function fetch_packages1($where){
$this->db->select('t3.temp_service_id,t4.name,t4.price,services.service_id');
$this->db->from('package_services as t1');
$this->db->join('services','services.service_id = t1.service_id', 'LEFT');
$this->db->join('template_services as t3','t3.temp_service_id = services.temp_service_id' , 'LEFT');
$this->db->join('package_master as t4', 't4.package_num = t1.package_num','LEFT');
$this->db->where($where);
$this->db->group_by('t1.package_num');
return $this->db->get()->row();
}
function fetch_service_details($where){
$this->db->select('services.price as fees,template_services.service_name');
$this->db->from('services');
$this->db->join('template_services','template_services.temp_service_id =
services.temp_service_id','LEFT');
$this->db->where($where);
return $this->db->get()->row();
}
Basically what I am trying to do is put a data object inside $array variable that is data coming from one table now what i did was push data from another query into $array1
Than at the end all i did was array_push into $array3 all the data from $array1 and $array2 to make them join together but
MY OUTPUT IS THIS :
[
{
"data": {
"temp_service_id": "3",
"name": "health checkup",
"price": "10000",
"service_id": "41"
},
"data2": [
{
"fees": "2000",
"service_name": "Anaesthesiologist"
},
{
"fees": "300",
"service_name": "Andrologist"
}
]
}
]
What am i missing here? i am really confused and can't understand how to push data2 array.
Thankyou in advance :)
Re-write one line in your Controller $array['data2'] = $array1; with $array->data['data2'] = $array1;.
It will put array data2 into the data index.
Working Demo
I came up with a solution finally after thinking about it a lot
$fetch_package_name = $this->$model_name->fetch($table_package_master,$where);
$array = [];
$array1 = [];
if($fetch_package_name){
for($i=0;$i<sizeof($fetch_package_name); $i++){
$where_r['t1.package_num'] = $fetch_package_name[$i]->package_num;
$where_r['t1.is_active'] = 'Y';
$where_r['services.is_active'] = 'Y';
$where_r['t4.is_active'] = 'Y';
$fetch_packages1 = $this->$model_name->fetch_packages1($where_r);
$array[$i]['name'] = $fetch_package_name[$i]->name;
$array[$i]['price'] = $fetch_package_name[$i]->price;
$where_re['t1.package_num'] = $fetch_package_name[$i]->package_num;
$where_re['t1.is_active'] = 'Y';
$where_re['services.is_active'] = 'Y';
$fetch_packages = $this->$model_name->fetch_packages2($where_re);
for($j=0; $j<sizeof($fetch_packages); $j++){
$array1[$j]['service_name'] = $fetch_packages[$j]->service_name;
$array1[$j]['price'] = $fetch_packages[$j]->price;
}
$array[$i]['data2'] = $array1;
}
// $this->response($array);
$array2['data'] = $array;
$array2['status'] = 10007;
// $data_response['data'] = $array;
$this->response($array2);
}
IT gave me the response that i desired in the first place.\
{
"data":[
{
"name":"Full body checkup",
"price":"5000",
"data2":[
{
"service_name":"Allergist",
"price":"23"
},
{
"service_name":"Andrologist",
"price":"300"
}
]
}
],
}
Cheers! happy coding :-)

Resources