Convert to array from database - arrays

From my database, I want to get this array
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"}
]
};
These are my tables :
INSERT INTO `event_date` (`id`, `date`) VALUES
(1, '2022-09-13'),
(2, '2022-09-30'),
(3, '2022-09-20');
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);
[{"id":"1","date":"2022-09-13","descript":"11","title":"111","id_event_date":"1"},{"id":"2","date":"2022-09-13","descript":"22","title":"22","id_event_date":"1"},{"id":"3","date":"2022-09-30","descript":"22","title":"22","id_event_date":"2"},{"id":"4","date":"2022-09-20","descript":"ss","title":"ss","id_event_date":"3"}]
I tried this
Future<dynamic> getData() async {
var url = 'http://xxxxxxxxxx/getEvents.php';
var res = await http.get(Uri.parse(url));
var response = json.decode(res.body);
Map<String, dynamic> mySelectedEvents = Map.fromIterable(response,
key: (item) => item['date'],
value: (item) =>
{'eventDescp': item['descript'], 'eventTitle': item['title']});
print(mySelectedEvents);
return mySelectedEvents;
}

I think the code that you have written is good, are you sure that your database does have more than two elements?

Related

for loop produces unexpected result in Python

I'm struggling with this 'simple' code. I have the following list of objects:
[
{
"element_id": "6185316",
"id": 123456,
"inv_part_id": 2345250,
"is_spare": true,
"num_sets": 191,
"part": {
"external_ids": {
"BrickOwl": [
"359273"
],
"NODEX": [
"17715",
"19385"
]
},
"name": "Bar 3L",
"part_cat_id": 32,
"part_num": "27808",
"print_of": null
},
"quantity": 1,
"set_num": "71043-1"
},
{
"element_id": "6185316",
"id": 654321,
"inv_part_id": 2345250,
"is_spare": true,
"num_sets": 191,
"part": {
"external_ids": {
"BrickOwl": [
"359273"
],
"NODEX": [
"17715",
"19385"
]
},
"name": "Bar 3L",
"part_cat_id": 32,
"part_num": "5861",
"print_of": null
},
"quantity": 1,
"set_num": "71043-1"
}]
My goal is to just add the value of part_num (inside PART object) to a list. I'm using the following for this:
final = []
count = 1
for x in spf:
for y in x["part"]["part_num"]:
final.append(y)
but it is appending each char instead of adding the complete value:
['2', '7', '8', '0', '8', '5', '8', '6', '1']
The expected output should be:
['27808', '5861']
What am I doing wrong?

How to interchange index of multiple array in javascript and create a new array

Following is my input data
{ menu_name: 'testmenu',
table_name: 'test_tbl',
field_name: [ 'booktitle', 'bookid', 'bookauthor' ],
field_type: [ 'varchar', 'int', 'varchar' ],
field_size: [ '55', '11', '100' ] }
How can i convert this data to following array format
['testmenu','test_tbl','booktitle','varchar','55']
['testmenu','test_tbl', 'bookid','int','11']
['testmenu','test_tbl','bookauthor','varchar','100']
You can achieve this with the help of Array map method,
let obj = {
menu_name: 'testmenu',
table_name: 'test_tbl',
field_name: ['booktitle', 'bookid', 'bookauthor'],
field_type: ['varchar', 'int', 'varchar'],
field_size: ['55', '11', '100']
}
let result = obj.field_name.map((x, i) => [obj.menu_name, obj.table_name, x, obj.field_type[i], obj.field_size[i]]);
console.log(result);

Traverse an array and get lowest 2 entries for a given name

I have an array with a key "name", and "points". There can be multiple entries for a particular name. What would be the ideal way to form a new array with name, points and a new key type based on points.
Example:
input:
[{"name":"A", "points": 9},
{"name":"A", "points": 5},
{"name":"A", "points": 4},
{"name":"A", "points": 1},
{"name":"A", "points": 3},
{"name":"A", "points": 6},
{"name":"B", "points": 5},
{"name":"B", "points": 1},
{"name":"B", "points": 2},
{"name":"B", "points": 3}]
Lowest points - typeA
Second lowest points - typeB
Output:
[{"name":"A", "points": 1, "type":"typeA"},
{"name":"A", "points": 3, "type":"typeB"},
{"name":"B", "points": 1, "type":"typeA"},
{"name":"B", "points": 2, "type":"typeB"}]
I think that this would be a good solution:
const input = [{"name":"A", "points": 9},
{"name":"A", "points": 5},
{"name":"A", "points": 4},
{"name":"A", "points": 1},
{"name":"A", "points": 3},
{"name":"A", "points": 6},
{"name":"B", "points": 5},
{"name":"B", "points": 1},
{"name":"B", "points": 2},
{"name":"B", "points": 3}];
//this function will be passed to Array's "reduce" function, and will return the item with the lowest points
const reduceLowest = (lowest, current) => current.points < lowest.points ? current : lowest;
//this function receives an item and returns a new item with an additional "type" property
const addType = (item, typeToAdd) => { return { name : item.name, points : item.points, type : typeToAdd } };
//this function receives an array and returns another array with its two lowests items (typeA and typeB)
const returnTypeATypeB = (arr) => {
var lowestTypeA = arr
.reduce(reduceLowest) //gets the lowest item
;
var lowestTypeB = arr
.filter((item) => item != lowestTypeA) //removes the item that already is the lowest from the array
.reduce(reduceLowest) //gets the lowest item
;
//return an array containing the typeA and typeB items
return [ addType(lowestTypeA, "typeA"), addType(lowestTypeB, "typeB")];
};
const output =
returnTypeATypeB(
input.filter((item) => item.name === "A")
) //gets typeA and typeB from the items which contains the name "A"
.concat( //concat the previous list with..
returnTypeATypeB(
input.filter((item) => item.name === "B")
) //typeA and typeB from the items which contains the name "B"
);
console.log(output);
//prints..
// [ { name: 'A', points: 1, type: 'typeA' },
// { name: 'A', points: 3, type: 'typeB' },
// { name: 'B', points: 1, type: 'typeA' },
// { name: 'B', points: 2, type: 'typeB' } ]

Yii2 return JSON format with array inside an array

I am trying to get these data below,
Table relations:
people(one) <---> (many) people_info (one) <---> (many) people_contact
in the following format,
people: {
p_id: 10,
p_price: 3.99,
people_info : [
{
pl_id: 3,
pl_state: 2,
pl_district: 6,
pl_latitude: 6.323434,
pl_longitude: 108.23499,
people_contact: [
{
plc_id: 2
},
{
plc_id: 1
}
]
},
{
pl_id: 2,
pl_state: 7,
pl_district: 12,
pl_latitude: 6.000434,
pl_longitude: 108.9910003,
people_contact: [
{
plc_id: 5
},
{
plc_id: 9
}
]
}
]
}
Currently with these controller codes,
class PeopleController extends Controller
{
public function actionPeople($params){
Yii::$app->response->format = Response::FORMAT_JSON;
....//some other codes//.....
$people= People::find()->select(['p_id', 'p_price'] )->where(['p_id' => $itemId])->one();
$info= PeopleContact::find()->with(['plPeople'])->asArray([])->all();
return array(
'people' => $people,
'info' => $info,
);
}
}
I got these,
"people": {
"p_id": "3",
"p_price": "32.42"
}, "locations": [{
"pl_id": "1",
"pl_people": "3",
"pl_title": "",
"pl_latitude": "6.16438700000000000000",
"pl_longitude": "102.28314649999993000000",
"pl_place": null,
"pl_premise": null,
"pl_street": "1",
"pl_area": "1",
"pl_postcode": "1",
"pl_district": "1",
"pl_state": "3",
"pl_country": 1,
"place": null,
"premise": null,
"street": null,
"area": null,
"postcode": null,
"district": null,
"state": null,
"country": "United Kingdom",
"contacts": [{
"plc_name": "joe",
"plc_phone": "123456",
"plc_email": null
}]
}]
}
How do I achieve it in the format mentioned at the top?
$output;
$people=People::find()->select(['p_id', 'p_price'] )->asArray()->all();
foreach($people as $person) {
$infos = PersonInfo::find()->where(['person_id' => $person->id])->asArray()->all();
foreach($infos as $info) {
$contacts = PersonContact::find()->where(['person_info_id' => $info->id])->asArray()->all();
foreach($contacts as $contact) {
$info['contacts'][] = $contact;
}
$person['info'][] = $info
}
$output['people'][] = $person
}
return $output;
You should loop through and fetch data like this: people > info > contact each next level relying on info fetched from the previous one. Then store it in the format you want such as demonstrated above.
This will output something like:
"people": [{
...
"info": [{
...
"contacts": [{
...
},{
...
}]
}]
},{
...
}]

Select a value from an array of hashes

From an array of hashes:
response = [
{"label"=>"cat", "name"=>"kitty", "id"=>189955},
{"label" => "dog", "name"=>"rex", "id" => 550081}
]
is there a way to write something like:
response.name.kitty
to retrieve the hash that contains this value:
{"label"=>"cat", "name"=>"kitty", "id"=>189955}
You can do this -
response.select{|x| x["name"] == "kitty"}.first
Use a Proc
response = [{"label"=>"cat", "name"=>"kitty", "id"=>189955},
{"label" => "dog", "name"=>"rex", "id" => 550081}]
finder = Proc.new {|k, v| response.find {|r| r[k] == v} }
Then
finder.call('name', 'rex')
# => {"label"=>"dog", "name"=>"rex", "id"=>550081}
finder.call('label', 'cat')
# => {"label"=>"cat", "name"=>"kitty", "id"=>189955}
You can also pass multiple conditions if required like this:
response = [
{"label"=>"cat", "name"=>"kitty", "id"=>189955},
{"label"=>"cat", "name"=>"kitty", "id"=>189956},
{"label"=>"cat", "name"=>"kitty", "id"=>189957},
{"label"=>"cat", "name"=>"meow", "id"=>189957},
{"label" => "dog", "name"=>"rex", "id" => 550081},
{"label" => "dog", "name"=>"tommy", "id" => 550082},
{"label" => "dog", "name"=>"rex", "id" => 550083}
]
> response.select{|h| h["label"] == "cat" && h["name"] == "kitty" && h["id"] == 189955}
=> [{"label"=>"cat", "name"=>"kitty", "id"=>189955}] # returns array of selected hashes
> response.find{|h| h["label"] == "cat" && h["name"] == "kitty" && h["id"] == 189955}
=> {"label"=>"cat", "name"=>"kitty", "id"=>189955} # returns first match element
if you're using Rails - just use .pluck
array_of_hashes = [
{ name: "Kate", city: "Minsk", country: "Belarus", id: 1 },
{ name: "Mike", city: "New York", country: "USA", id: 2 },
{ name: "Aleh", city: "Warsaw", country: "Poland", id: 3},
]
>> array_of_hashes.pluck(:name)
>>
>> [ "Kate", "Mike", "Aleh" ]

Resources