Convert JSON date date to Timestamp Field - snowflake-cloud-data-platform

I have source data in JSON column in snowflake and need to convert to timestamp field.
Source data:
[
{
"end_time_of_day_of_week": {
"day_of_week": "TUESDAY",
"time_of_day": {
"hours": 23,
"minutes": 59,
"nanos": null,
"seconds": 59
}
},
"start_time_of_day_of_week": {
"day_of_week": "TUESDAY",
"time_of_day": {
"hours": null,
"minutes": null,
"nanos": null,
"seconds": null
}
}
},
{
"end_time_of_day_of_week": {
"day_of_week": "WEDNESDAY",
"time_of_day": {
"hours": 23,
"minutes": 59,
"nanos": null,
"seconds": 59
}
},
"start_time_of_day_of_week": {
"day_of_week": "WEDNESDAY",
"time_of_day": {
"hours": null,
"minutes": null,
"nanos": null,
"seconds": null
}
}
},
{
"end_time_of_day_of_week": {
"day_of_week": "THURSDAY",
"time_of_day": {
"hours": 23,
"minutes": 59,
"nanos": null,
"seconds": 59
}
},
"start_time_of_day_of_week": {
"day_of_week": "THURSDAY",
"time_of_day": {
"hours": null,
"minutes": null,
"nanos": null,
"seconds": null
}
}
},
{
"end_time_of_day_of_week": {
"day_of_week": "SATURDAY",
"time_of_day": {
"hours": 23,
"minutes": 59,
"nanos": null,
"seconds": 59
}
},
"start_time_of_day_of_week": {
"day_of_week": "SATURDAY",
"time_of_day": {
"hours": null,
"minutes": null,
"nanos": null,
"seconds": null
}
}
}
]
Target output 2 column with each days time (null will be replaced by zero):
|| start_time || end_time ||
TUESDAY 00:00 TUESDAY 23:59
WEDNESDAY 00:00 WEDNESDAY 23:59
THURSDAY 00:00 THURSDAY 23:59
SATURDAY 00:00 SATURDAY 23:59
Tuesday 23:

So given the data is repeated, I trimmed it to two rows:
with data(json) as (
select parse_json('[
{
"end_time_of_day_of_week": {
"day_of_week": "TUESDAY", "time_of_day": { "hours": 23, "minutes": 59, "nanos": null, "seconds": 59 }
},
"start_time_of_day_of_week": {
"day_of_week": "TUESDAY", "time_of_day": { "hours": null, "minutes": null, "nanos": null, "seconds": null }
}
},
{
"end_time_of_day_of_week": {
"day_of_week": "WEDNESDAY", "time_of_day": { "hours": 23, "minutes": 58, "nanos": null, "seconds": 59 }
},
"start_time_of_day_of_week": {
"day_of_week": "WEDNESDAY", "time_of_day": { "hours": null, "minutes": null, "nanos": null, "seconds": null }
}
}
]')
)
so using FLATTEN to unroll the ARRAY, and then accessing the fields, you can use the values. I using LPAD to make things 2 characters wide, and ZEROIFNULL to handle the variant nulls.
select f.value:"start_time_of_day_of_week" as s
,f.value:"end_time_of_day_of_week" as e
,s:day_of_week as s_dow
,s:time_of_day as s_tod
,e:day_of_week as e_dow
,e:time_of_day as e_tod
,lpad(zeroifnull(s_tod:hours::int),2,0) as s_h
,lpad(zeroifnull(s_tod:minutes::int),2,0) as s_m
,zeroifnull(s_tod:seconds::int) as s_s
,zeroifnull(s_tod:nano::int) as s_n
,lpad(zeroifnull(e_tod:hours::int),2,0) as e_h
,lpad(zeroifnull(e_tod:minutes::int),2,0) as e_m
,zeroifnull(e_tod:seconds::int) as e_s
,zeroifnull(e_tod:nano::int) as e_n
,concat( s_dow, ' ', s_h, ':', s_m ) as start_time
,concat( e_dow, ' ', e_h, ':', e_m ) as end_time
from data as d
,table(flatten(input=>d.json)) f
gives:
S
E
S_DOW
S_TOD
E_DOW
E_TOD
S_H
S_M
S_S
S_N
E_H
E_M
E_S
E_N
START_TIME
END_TIME
{ "day_of_week": "TUESDAY", "time_of_day": { "hours": null, "minutes": null, "nanos": null, "seconds": null } }
{ "day_of_week": "TUESDAY", "time_of_day": { "hours": 23, "minutes": 59, "nanos": null, "seconds": 59 } }
"TUESDAY"
{ "hours": null, "minutes": null, "nanos": null, "seconds": null }
"TUESDAY"
{ "hours": 23, "minutes": 59, "nanos": null, "seconds": 59 }
00
00
0
0
23
59
59
0
TUESDAY 00:00
TUESDAY 23:59
{ "day_of_week": "WEDNESDAY", "time_of_day": { "hours": null, "minutes": null, "nanos": null, "seconds": null } }
{ "day_of_week": "WEDNESDAY", "time_of_day": { "hours": 23, "minutes": 58, "nanos": null, "seconds": 59 } }
"WEDNESDAY"
{ "hours": null, "minutes": null, "nanos": null, "seconds": null }
"WEDNESDAY"
{ "hours": 23, "minutes": 58, "nanos": null, "seconds": 59 }
00
00
0
0
23
58
59
0
WEDNESDAY 00:00
WEDNESDAY 23:58
which can be simplified to:
select
start_time
,end_time
from (
select f.value:"start_time_of_day_of_week" as s
,f.value:"end_time_of_day_of_week" as e
,lpad(zeroifnull(s:time_of_day:hours::int),2,0) as s_h
,lpad(zeroifnull(s:time_of_day:minutes::int),2,0) as s_m
,lpad(zeroifnull(e:time_of_day:hours::int),2,0) as e_h
,lpad(zeroifnull(e:time_of_day:minutes::int),2,0) as e_m
,concat( s:day_of_week, ' ', s_h, ':', s_m ) as start_time
,concat( e:day_of_week, ' ', e_h, ':', e_m ) as end_time
from data as d
,table(flatten(input=>d.json)) f
)
START_TIME
END_TIME
TUESDAY 00:00
TUESDAY 23:59
WEDNESDAY 00:00
WEDNESDAY 23:58

You need to use the Snowflake flatten function to convert the JSON array to rows.
Note that your desired output is not really a timestamp. It's a string (varchar). If there were enough information to construct a timestamp, the SQL could do that and output it with a format string the way you have it. However, there's not enough information to create a timestamp so this shows how to make it a varchar formatted as your target output.
create or replace table T1(v variant);
insert into T1 select parse_json($$ >>> Paste your JSON here <<< $$);
select * from T1; -- Make sure your JSON is in the table correctly.
select * from T1, table(flatten(v)); -- Start the flattening and extraction with this.
select VALUE:start_time_of_day_of_week.day_of_week::string || ' ' ||
nvl(VALUE:start_time_of_day_of_week.time_of_day.hours::string, '00') || ':' ||
nvl(VALUE:start_time_of_day_of_week.time_of_day.minutes::string, '00')
as START_TIME
,VALUE:end_time_of_day_of_week.day_of_week::string || ' ' ||
nvl(VALUE:end_time_of_day_of_week.time_of_day.hours::string, '00') || ':' ||
nvl(VALUE:end_time_of_day_of_week.time_of_day.minutes::string, '00')
as END_TIME
from T1, table(flatten(v));
Output:
START_TIME
END_TIME
TUESDAY 00:00
TUESDAY 23:59
WEDNESDAY 00:00
WEDNESDAY 23:59
THURSDAY 00:00
THURSDAY 23:59
SATURDAY 00:00
SATURDAY 23:59

Related

Group array of dates and format to schedule

I need to group an array of dates and then format the group of dates into a schedule format.
Possible labels could be:
Weekdays (from Mon to Fri)
Weekends (Sat and Sun)
Monday-Tuesday (range of days with same schedule)
Wednesday (specific day with unique schedule)
Thursday, Saturday (specific group of days with same schedule)
For example:
Input Data
[
{
day: "monday",
start_time: "09:00",
end_time: "18:00"
},
{
day: "tuesday",
start_time: "09:00",
end_time: "18:00"
},
{
day: "wednesday",
start_time: "09:00",
end_time: "18:00"
},
{
id: 25,
day: "thursday",
start_time: "09:00",
end_time: "18:00"
},
{
day: "friday",
start_time: "09:00",
end_time: "18:00"
},
{
day: "saturday",
start_time: "10:00",
end_time: "17:00"
},
{
day: "sunday",
start_time: "10:00",
end_time: "17:00"
}
]
Expected Output
[
{
label: 'All weekdays', // Mon-Fri
value: '09:00 - 18:00',
},
{
label: 'Weekend', // Sat-Sun
value: '10:00 - 17:00',
},
];
And the output can be as follows, if start_time and end_time are different for each day
[
{
label: 'Monday', // one day
value: '09:00 - 20:00',
},
{
label: 'Tuesday, Thursday', // specific days with same schedule
value: '10:00 - 19:00',
},
{
label: 'Wednesday', // one day
value: '12:00 - 20:00',
},
{
label: 'Friday - Sunday', // range of days with same schedule
value: '10:00 - 17:00',
},
];
CodeSandbox with template - link
An approach for solving the OP's problem breaks down into ...
grouping/collecting all items (or day names) of a specific time-schedule/range
and creating the final result upon this first grouped and aggregated data,
... which one straightforwardly can implement by a reduce and a mapping task that would be accompanied by some helper functions which for example would ...
normalize any weekday's name
compare weekdays by their names
acquire the correct label of a time-schedule by e.g. an ordered list of unique weekday names.
The reduce task is going to create an object where each key already represent the final result's value, a string which represents a time range like e.g. '09:00 - 18:00' and where each of such a key's value is an array of each of the processed item's day-values (the latter being a string which represents a weekday's name with neither specific nor reliable latter-casing like e.g. 'monday' or 'Monday').
The map task would process the entries of such an above described object. Each entry's time-schedule related key gets assigned as the final items's value property. And each entry's weekday related value (an array of weekday names) is the base of computing the final item's label property.
Implementation ...
// helpers.
function normalizeNameOfWeekday(value) {
return value
.toLowerCase()
.replace(/^(\p{L})(.*)$/u, (_, first, last) =>
[first.toUpperCase(), last].join('')
);
}
function compareWeekdaysByName(a, b) {
const lookup = {
monday: 0, tuesday: 1, wednesday: 2,
thursday: 3, friday: 4,
saturday: 5, sunday: 6,
};
return lookup[a.toLowerCase()] - lookup[b.toLowerCase()];
}
function getTimeScheduleLabel(days) {
const lookup = {
monday_tuesday: 'Monday & Tuesday',
monday_tuesday_wednesday: 'Monday - Wednesday',
monday_tuesday_wednesday_thursday: 'Monday - Thursday',
monday_tuesday_wednesday_thursday_friday: 'All working days',
monday_tuesday_wednesday_thursday_friday_saturday: 'Monday - Saturday',
monday_tuesday_wednesday_thursday_friday_saturday_sunday: 'Every day of the week',
tuesday_wednesday: 'Tuesday & Wednesday',
tuesday_wednesday_thursday: 'Tuesday - Thursday',
tuesday_wednesday_thursday_friday: 'Tuesday - Friday',
tuesday_wednesday_thursday_friday_saturday: 'Tuesday - Saturday',
tuesday_wednesday_thursday_friday_saturday_sunday: 'Tuesday - Sunday',
wednesday_thursday: 'Wednesday & Thursday',
wednesday_thursday_friday: 'Wednesday - Friday',
wednesday_thursday_friday_saturday: 'Wednesday - Saturday',
wednesday_thursday_friday_saturday_sunday: 'Wednesday - Sunday',
thursday_friday: 'Thursday & Friday',
thursday_friday_saturday: 'Thursday - Saturday',
thursday_friday_saturday_sunday: 'Thursday - Sunday',
friday_saturday: 'Friday & Saturday',
friday_saturday_sunday: 'Friday - Sunday',
saturday_sunday: 'All weekend',
};
const scheduleFingerprint = [
// set of unique day-names.
...new Set(days)
]
// ordered list (of unique day-names).
.sort(compareWeekdaysByName)
// comparable schedule-fingerprint.
.join('_').toLowerCase();
return lookup[scheduleFingerprint] ?? days.map(normalizeNameOfWeekday).join(', ');
}
// reducer.
function collectDayOfSameTimeSchedule(index, { day, start_time, end_time }) {
const scheduleKey = `${ start_time } - ${ end_time }`;
// create and/or access the array of
// day-names of the same time-schedule
// and push another matching name into it.
(index[scheduleKey] ??= []).push(day);
return index;
}
// mapper.
function createTimeScheduleFromEntry([scheduleKey, listOfSameTimeScheduleDays]) {
return {
label: getTimeScheduleLabel(listOfSameTimeScheduleDays),
value: scheduleKey,
}
}
const sampleData_01 = [{
day: "monday", start_time: "09:00", end_time: "18:00",
}, {
day: "tuesday", start_time: "09:00", end_time: "18:00",
}, {
day: "wednesday", start_time: "09:00", end_time: "18:00",
}, {
id: 25, day: "thursday", start_time: "09:00", end_time: "18:00",
}, {
day: "friday", start_time: "09:00", end_time: "18:00",
}, {
day: "saturday", start_time: "10:00", end_time: "17:00",
}, {
day: "sunday", start_time: "10:00", end_time: "17:00",
}];
const sampleData_02 = [{
day: "monday", start_time: "09:00", end_time: "20:00",
}, {
day: "tuesday", start_time: "10:00", end_time: "19:00",
}, {
day: "wednesday", start_time: "12:00", end_time: "20:00",
}, {
id: 25, day: "thursday", start_time: "10:00", end_time: "19:00",
}, {
day: "friday", start_time: "10:00", end_time: "17:00",
}, {
day: "saturday", start_time: "10:00", end_time: "17:00",
}, {
day: "sunday", start_time: "10:00", end_time: "17:00",
}];
console.log(
'sample-data with 2 time-schedules ...',
Object
.entries(
sampleData_01
.reduce(collectDayOfSameTimeSchedule, {})
)
.map(createTimeScheduleFromEntry)
);
console.log(
'sample-data with 4 time-schedules ...',
Object
.entries(
sampleData_02
.reduce(collectDayOfSameTimeSchedule, {})
)
.map(createTimeScheduleFromEntry)
);
console.log('\n');
console.log(
'intermediate reducer-step of ... sample-data with 2 time-schedules ...',
sampleData_01
.reduce(collectDayOfSameTimeSchedule, {})
);
console.log(
'intermediate reducer-step of ... sample-data with 4 time-schedules ...',
sampleData_02
.reduce(collectDayOfSameTimeSchedule, {})
);
.as-console-wrapper { min-height: 100%!important; top: 0; }
I have written a snippet, it might help
var scheduleInfo = [
{
day: "monday",
start_time: "09:00",
end_time: "18:00"
},
{
day: "tuesday",
start_time: "09:00",
end_time: "18:00"
},
{
day: "wednesday",
start_time: "09:00",
end_time: "18:00"
},
{
id: 25,
day: "thursday",
start_time: "08:00",
end_time: "18:00"
},
{
day: "friday",
start_time: "09:00",
end_time: "18:00"
},
{
day: "saturday",
start_time: "10:00",
end_time: "17:00"
},
{
day: "sunday",
start_time: "10:00",
end_time: "17:00"
}
]
var tempOutput = [];
var output = [];
let allDays = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"]
var weekdays = ["monday", "tuesday", "wednesday", "thursday", "friday"]
weekdays = weekdays.sort();
//sort according to schedule
for (let i in scheduleInfo) {
let sch = scheduleInfo[i];
if (!allValue.includes(sch.start_time + sch.end_time)) {
allValue.push(sch.start_time + sch.end_time);
tempOutput.push({
label: sch.day,
start_time: sch.start_time,
end_time: sch.end_time
})
} else {
for (let j in tempOutput) {
if (tempOutput[j].start_time === sch.start_time && tempOutput[j].end_time === sch.end_time) {
tempOutput[j].label = tempOutput[j].label + ',' + sch.day;
}
}
}
}
//logic to identify label.
for (let i in tempOutput) {
var days = tempOutput[i].label.split(",");
var label = days[0];
var tempLDay = "";
for (let j = 1; j < days.length; j++) {
if (!tempLDay) {
label += days[j];
tempLDay = days[j];
}
//check for consecutive days
let daysDiff = allDays.indexOf(days[j - 1]) % 7 - allDays.indexOf(days[j]) % 7;
if (daysDiff == -1 || daysDiff === 1) {
label = label.replace(tempLDay, "-" + days[j]);
tempLDay = "-" + days[j]
} else {
label += "," + days[j]
tempLDay = "";
}
}
if (label == "monday-friday") {
label = "All weekdays"
} else if (label == "saturday-sunday") {
label = "Weekend"
}
output.push({
label: label,
value: tempOutput[i].start_time + ' - ' + tempOutput[i].end_time
})
}
console.log(output);
I have a similar solution on a project of mine, you could try to make any necessary changes to the code if you don't like the result.
You give an initial constants with an array of weekend and weekdays, and then comparing the inputed dated data you generate the desired output.
function formatDates(dates) {
const result = [];
const weekdays = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday'];
const weekends = ['saturday', 'sunday'];
let start = 0;
let end = 0;
while (start < dates.length) {
let label = '';
let value = '';
let same = true;
end = start;
while (end < dates.length - 1 && same) {
end++;
same = dates[end].start_time === dates[end - 1].start_time && dates[end].end_time === dates[end - 1].end_time;
}
if (weekdays.includes(dates[start].day) && weekdays.includes(dates[end].day)) {
label = 'All weekdays';
value = `${dates[start].start_time} - ${dates[start].end_time}`;
} else if (weekends.includes(dates[start].day) && weekends.includes(dates[end].day)) {
label = 'Weekend';
value = `${dates[start].start_time} - ${dates[start].end_time}`;
} else if (same) {
if (weekdays.includes(dates[start].day)) {
label = `${dates[start].day[0].toUpperCase()}${dates[start].day.slice(1)} - ${dates[end].day[0].toUpperCase()}${dates[end].day.slice(1)}`;
} else if (weekends.includes(dates[start].day)) {
label = `${dates[start].day[0].toUpperCase()}${dates[start].day.slice(1)} - ${dates[end].day[0].toUpperCase()}${dates[end].day.slice(1)}`;
} else {
label = `${dates[start].day[0].toUpperCase()}${dates[start].day.slice(1)}`;
}
value = `${dates[start].start_time} - ${dates[start].end_time}`;
} else {
for (let i = start; i <= end; i++) {
result.push({
label: `${dates[i].day[0].toUpperCase()}${dates[i].day.slice(1)}`,
value: `${dates[i].start_time} - ${dates[i].end_time}`
});
}
}
if (label) {
result.push({ label, value });
}
start = end + 1;
}
return result;
}

Angularjs - html table with months and weeks

I want somthing like this, a table with months and weeks number:
I made this JS Ffiddle: https://jsfiddle.net/2fxq4pc9/
function TodoCtrl($scope) {
$scope.filter = {
"year": ''+new Date().getFullYear()
};
$scope.months = [
{"name": "Jan","number": 1, "totalWeeks": null, "weeks": null},
{"name": "Feb","number": 2, "totalWeeks": null, "weeks": null},
{"name": "Mar","number": 3, "totalWeeks": null, "weeks": null},
{"name": "Apr","number": 4, "totalWeeks": null, "weeks": null},
{"name": "May","number": 5, "totalWeeks": null, "weeks": null},
{"name": "Jun","number": 6, "totalWeeks": null, "weeks": null},
{"name": "Jul","number": 7, "totalWeeks": null, "weeks": null},
{"name": "Aug","number": 8, "totalWeeks": null, "weeks": null},
{"name": "Sep","number": 9, "totalWeeks": null, "weeks": null},
{"name": "Oct","number": 10, "totalWeeks": null, "weeks": null},
{"name": "Nov","number": 11, "totalWeeks": null, "weeks": null},
{"name": "Dec","number": 12, "totalWeeks": null, "weeks": null}
];
$scope.getTotalWeekOfAMonth = function(year, month) {
var firstOfMonth = new Date(year, month - 1, 1);
var day = firstOfMonth.getDay() || 6;
day = day === 1 ? 0 : day;
if (day) { day-- }
var diff = 7 - day;
var lastOfMonth = new Date(year, month, 0);
var lastDate = lastOfMonth.getDate();
if (lastOfMonth.getDay() === 1) {
diff--;
}
var result = Math.ceil((lastDate - diff) / 7);
return result + 1;
}
$scope.createWeeksNumberList = function() {
$scope.months.forEach(function(element) {
var weekTotals = $scope.getTotalWeekOfAMonth($scope.filter.year, element.number);
var obj = [];
for (let week = 1; week <= weekTotals; week++) {
obj.push({"weekNumber": week, "flag": null });
}
element.weeks = obj;
element.totalWeeks = weekTotals;
});
}
$scope.createWeeksNumberList();
}
Is there a way to improve it and to show numbers of weeks consecutive? 1 to 52 (splitted by months).
The current one seems a bit slow and ugly (I'm concerned about the javascript code and not the css style).
Thanks.

transform extracting data from an array into extracting from a csv file

this is a working code that prints statics from covid data [], run it so you can understand, i want to turn this code to read not from this covid data[] but from a csv file that i have full with data same like in covid data []
i have no idea how to do it , if you can please copy the working code, thank you a lot!
this array covid data [] is a part of the csv file so you can understand.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
unsigned int SNo;
char ObservationDate[11];
char Province_State[50];
char Country_Region[50];
char Last_Update[50];
float Confirmed;
float Deaths;
float Recovered;
}covid;
void printGraph(int number) {
int i;
for (i = 0; i < number; i++) {
printf("*");
}
printf("\n");
}
void printDistribution(covid data[], int datalength, char country[50], char date[11]) {
int i;
for (i = 0; i < datalength; i++) {
if (strcmp(country, data[i].Country_Region) == 0) {
if (strcmp(date, data[i].ObservationDate) == 0) {
printf("Total Cases: %f", data[i].Confirmed);
printGraph(data[i].Confirmed);
printf("Total Deaths: %f", data[i].Deaths);
printGraph(data[i].Deaths);
printf("Total Recovered: %f", data[i].Recovered);
printGraph(data[i].Recovered);
float fatalityRate = (data[i].Deaths / data[i].Confirmed) * 100;
float recoveryRate = (data[i].Recovered / data[i].Confirmed) * 100;
printf("Fatality Rate: %f%%\n", fatalityRate);
printf("Recovery Rate: %f%%\n", recoveryRate);
}
}
}
}
int main(int argc, char** argv) {
covid data[] = {
{1, "1/22/2020", "Anhui", "Mainland China", "1/22/2020 5:00:00 PM", 1, 0 , 0},
{2, "1/22/2020", "Beijing", "Mainland China", "1/22/2020 5:00:00 PM", 14, 0 , 0},
{3, "1/22/2020", "Fujian", "Mainland China", "1/22/2020 5:00:00 PM", 6, 0 , 0},
{4, "1/22/2020", "Washington", "US", "1/22/2020 5:00:00 PM", 1, 0 , 0},
{5, "1/22/2020", "Beirut", "Lebanon", "1/22/2020 5:00:00 PM", 1, 0 , 0},
{6, "2/22/2020", "Anhui", "Mainland China", "2020-02-22T07:43:03", 989, 6 , 597},
{7, "2/22/2020", "Beijing", "Mainland China", "1/22/2020 5:00:00 PM", 399, 4 , 178},
{8, "2/22/2020", "Fujian", "Mainland China", "1/22/2020 5:00:00 PM", 293, 1 , 162},
{9, "2/22/2020", "Washington", "US", "1/22/2020 5:00:00 PM", 150, 10 , 96},
{10, "2/13/2020", "Beirut", "Lebanon", "1/22/2020 5:00:00 PM", 50, 10 , 15},
{11, "3/13/2020", "Anhui", "Mainland China", "1/22/2020 5:00:00 PM", 1500, 20 , 785},
{12, "3/13/2020", "Beijing", "Mainland China", "1/22/2020 5:00:00 PM", 450, 50 , 300},
{13, "3/13/2020", "Fujian", "Mainland China", "1/22/2020 5:00:00 PM", 6, 0 , 0},
{14, "3/13/2020", "Washington", "US", "1/22/2020 5:00:00 PM", 1, 0 , 0},
{15, "3/13/2020", "Beirut", "Lebanon", "1/22/2020 5:00:00 PM", 1, 0 , 0},
{16, "4/15/2020", "Anhui", "Mainland China", "2020-02-22T07:43:03", 989, 6 , 597},
{17, "4/15/2020", "Beijing", "Mainland China", "1/22/2020 5:00:00 PM", 399, 4 , 178},
{18, "4/15/2020", "Fujian", "Mainland China", "1/22/2020 5:00:00 PM", 293, 1 , 162},
{19, "4/15/2020", "Washington", "US", "1/22/2020 5:00:00 PM", 150, 10 , 96},
{20, "4/15/2020", "Beirut", "Lebanon", "1/22/2020 5:00:00 PM", 50, 10 , 15},
};
char country[] = "US";
char date[] = "4/15/2020";
printDistribution(data, 20, country, date);
return 0;
}

sorting a json array programmatically

This is th json, this need to be filtered based on the "testType" equal to 'R' also had to sort based on "createdDate"
{
"code": null,
"message": "Total 1 records found",
"result": {
"size": 0,
"dob": 412977600000,
"sex": "F",
"visitMasts": [
{
"createdBy": 61,
"visitId": 1235,
"ordersList": [
{
"testId": 4,
"ordersDto": {
"orderId": 50815,
"testType": "R",
"createdDate": 1479277029456
}
},
{
"testId": 4,
"ordersDto": {
"orderId": 50807,
"testType": "R",
"createdDate": 1479016014784
}
}
]
}
]
}
}
The filtering is achieved using this,
vm user = response.data.result;
if (vm.user.visitMasts[0].ordersList != null && vm.user.visitMasts[0].ordersList.length > 0) {
radioTestDetails = filterFilter(vm.user.visitMasts[0].ordersList, {
ordersDto: {
testType: 'R'
}
});
}
How can I sort the value based on this
response.data.result in that visitMasts -> orderList[] -> createdDate

Laravel sort array by created_at

I need to sort my json array in chronological order by it's created_at timestamps.
[{
"id": 1,
"message": "hello",
"company_id": 7,
"investor_id": 35,
"match_id": 2,
"created_at": "2015-07-01 12:56:34",
"updated_at": "2015-07-01 12:56:34"
}, {
"id": 2,
"message": "helloWorld",
"company_id": 7,
"investor_id": 35,
"match_id": 2,
"created_at": "2015-07-01 12:56:53",
"updated_at": "2015-07-01 12:56:53"
}, {
"id": 3,
"message": "sup",
"company_id": 7,
"investor_id": 35,
"match_id": 2,
"created_at": "2015-07-01 13:12:53",
"updated_at": "2015-07-01 13:12:53"
}, {
"id": 4,
"message": "sup",
"company_id": 7,
"investor_id": 35,
"match_id": 2,
"created_at": "2015-07-01 13:13:04",
"updated_at": "2015-07-01 13:13:04"
}, {
"id": 5,
"message": "sup",
"company_id": 7,
"investor_id": 35,
"match_id": 2,
"created_at": "2015-07-01 15:06:39",
"updated_at": "2015-07-01 15:06:39"
}, {
"id": 1,
"message": "yo yo ",
"investor_id": 35,
"company_id": 7,
"match_id": 2,
"created_at": "2015-07-01 22:09:36",
"updated_at": "-0001-11-30 00:00:00"
}, {
"id": 2,
"message": "sup nigga",
"investor_id": 35,
"company_id": 7,
"match_id": 2,
"created_at": "2015-07-01 14:00:00",
"updated_at": "-0001-11-30 00:00:00"
}]
Can anyone teach me how do i have tried many solutions in stackoverflow . Many of them says array cannot be used with "sortBy" .
This is part of my code :
$companyMessage = Company_Message::where('match_id','=',$match_id);
$investorMessage = Investor_Message::where('match_id','=',$match_id);
$message = array();
if($companyMessage->count()>0 || $investorMessage->count() > 0){
if($lastActivityDate == null ){
//load all messages before
if($companyMessage !=null){
foreach ($companyMessage->get() as $cm) {
array_push($message,$cm);
}
}
if($investorMessage !=null){
foreach($investorMessage->get() as $im){
array_push($message,$im);
}
}
return $message ;
}
I think you can do this using use a laravel database collection api instead of array and add item to collection and use sortBy method on collection,
$col = new \Illuminate\Database\Eloquent\Collection();
if ($companyMessage != null) {
foreach($companyMessage - > get() as $cm) {
$col->add($cm);
}
}
if ($investorMessage != null) {
foreach($investorMessage - > get() as $im) {
$col->add($im);
}
}
$col = $col->sortBy('created_at');
//return the json
return Response::json($jsonArr->toArray());
--- OR ----
Try this but i didn't tested it. If this works then this would be the best way to do this.
$companyMessage = Company_Message::where('match_id','=',$match_id);
$investorMessage = Investor_Message::where('match_id','=',$match_id);
//$companyMessage & $investorMessage both are laravel database collection,
// so you can use merge method on collection to merge these two collections.
$allResults = $companyMessage->merge($investorMessage);
//use laravel collection sort method to sort the collection by created_at
$allResults = $allResults->sortBy('created_at');
//return the json
return Response::json($allResults->toArray());
if($companyMessage !=null){
foreach ($companyMessage->get() as $cm) {
array_push($message,$cm);
}
}
if($investorMessage !=null){
foreach($investorMessage->get() as $im){
array_push($message,$im);
}
}
$message = array_values(array_sort($message, function ($value) {
return $value['created_at'];
}));
Hey man , i found a better solution to sort my array. The answer can be found at laravel docs
http://laravel.com/docs/5.1/helpers#method-array-sort

Resources