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
Related
[
{
"id": 200,
"date_created": "2021-01-14T17:15:55",
"sale": "2500.00",
},
{
"id": 201,
"date_created": "2021-01-15T15:10:30",
"sale": "2000.00",
},
{
"id": 202,
"date_created": "2021-02-4T11:14:10",
"sale": "4000.00",
}
]
I am unable to sum it by the monthly basis in react js or next js.
Can someone guide me on how can I do it in React?
I want the output as:
monthly basis.
For Jan total sum = 4500
For Feb total sum = 4000
etc...
You have to browse your array and to add each sale.
Example :
const a = [
{
"id": 200,
"date_created": "2021-01-14T17:15:55",
"sale": "2500.00",
},
{
"id": 201,
"date_created": "2021-01-15T15:10:30",
"sale": "2000.00",
},
{
"id": 202,
"date_created": "2021-02-4T11:14:10",
"sale": "4000.00",
}
]
const sum = a.reduce((previous, current) => previous + new Number(current.sale), 0)
console.log(sum)
I'm using api to get the response array, I'm trying to map the "id" under the "quiz_records" array but it returns undefined. I think that my code are correct.
This is my attempt.
array
"quizRemarks": [
{
"id": 160,
"user_id": 1,
"quiz_id": 18,
"module_id": 29,
"number_of_correct_answers": 2,
"created_at": "2021-10-15T03:52:52.000000Z",
"updated_at": "2021-10-15T03:52:52.000000Z",
"time_started": null,
"time_finished": null,
"remarks": 1,
"quiz_records": [
{
"id": 27,
"user_scores_id": 160,
"question_id": 2,
"user_answers": "DriverPH",
"remarks_correct_incorrect": "1",
"created_at": null,
"updated_at": null,
"question_text": "What is the name of this application?"
},
{
"id": 28,
"user_scores_id": 160,
"question_id": 2,
"user_answers": "Red",
"remarks_correct_incorrect": "1",
"created_at": null,
"updated_at": null,
"question_text": "What traffic light color tells you to stop before the intersection?"
}
]
}
]
ts
this.quiz_records = res['quizRemarks'].map(res => res['quiz_records'].id);
console.log(this.quiz_records);
quizRemarks is an array of objects containing an array of quiz_records. Try this to get a flat list of ids of quiz_records:
this.quiz_records = [];
this.quizRemarks.forEach(remark => {
this.quiz_records.push(...remark.quiz_records.map(rec => rec.id));
});
Below code will work----
this.quiz_records = res['quizRemarks'].map(res => res['quiz_records'].map(r => r.id));
You're truing to get an id property from an array, what it inpossible.
You can use nested map + flat() array method.
const result = res['quizRemarks'].map(remarks => {
return remarks['quiz_records'].map(record => record.id);
}).flat();
So I have successfully managed to parse the JSON data shown below:
[
{
"IsRecentlyVerified": false,
"ID": 136888,
"UUID": "254B0B07-E7FC-4B4B-A37C-899BCB9D7261",
"DataProviderID": 18,
"DataProvidersReference": "0a9fdbb17feb6ccb7ec405cfb85222c4",
"OperatorID": 3,
"UsageTypeID": 1,
"AddressInfo": {
"ID": 137234,
"Title": "Ballee Road Park & Share",
"AddressLine1": "Ballee Road",
"Town": "Ballymena",
"Postcode": "BT42 2HD",
"CountryID": 1,
"Latitude": 54.844648,
"Longitude": -6.273606,
"AccessComments": "Ballee Road Park and Share, Ballymena",
"RelatedURL": "http://pod-point.com",
"Distance": 3.812940207797744,
"DistanceUnit": 2
},
"Connections": [
{
"ID": 191571,
"ConnectionTypeID": 25,
"Reference": "1",
"StatusTypeID": 50,
"LevelID": 2,
"Amps": 32,
"Voltage": 400,
"PowerKW": 22,
"CurrentTypeID": 20
},
{
"ID": 191572,
"ConnectionTypeID": 25,
"Reference": "2",
"StatusTypeID": 50,
"LevelID": 2,
"Amps": 32,
"Voltage": 400,
"PowerKW": 22,
"CurrentTypeID": 20
}
],
"StatusTypeID": 0,
"DateLastStatusUpdate": "2020-02-21T15:15:00Z",
"MetadataValues": [
{
"ID": 6740,
"MetadataFieldID": 4,
"ItemValue": "Contains public sector information licensed under the Open Government Licence v2.0. http://www.nationalarchives.gov.uk/doc/open-government-licence/version/2/"
}
],
"DataQualityLevel": 3,
"DateCreated": "2019-12-24T05:23:00Z",
"SubmissionStatusTypeID": 100
},
{
"IsRecentlyVerified": false,
"ID": 48636,
"UUID": "69C483E6-E271-4315-A56F-E3747EA59D52",
"DataProviderID": 1,
"OperatorID": 93,
"OperatorsReference": "SC99",
"UsageTypeID": 4,
"UsageCost": "Free",
"AddressInfo": {
"ID": 48982,
"Title": "Dunsilly Park and Ride, Dunsilly Roundabout",
"AddressLine1": "Dunsilly Park and Ride, Dunsilly Roundabout,",
"Town": "Antrim",
"Postcode": "BT41 2JH",
"CountryID": 1,
"Latitude": 54.74636,
"Longitude": -6.234244,
"Distance": 4.081140533868653,
"DistanceUnit": 2
},
"Connections": [
{
"ID": 60091,
"ConnectionTypeID": 25,
"Reference": "1",
"StatusTypeID": 50,
"LevelID": 2,
"Amps": 32,
"Voltage": 400,
"PowerKW": 22,
"CurrentTypeID": 20,
"Quantity": 2
}
],
With the data struct file:
import Foundation
struct PublicCharger: Decodable {
let AddressInfo: AddressInfo
let Connections: [Connections]
}
struct AddressInfo: Decodable {
let Title: String
let Latitude: Double
let Longitude: Double
}
struct Connections: Decodable {
let StatusTypeID: Int
let ConnectionTypeID: Int
let PowerKW: Int
}
In my View Controller:
let decodedData = try decoder.decode([PublicCharger].self, from: data)
if !decodedData.isEmpty {
//print("Ran")
//print("Data: \(decodedData[0].AddressInfo.Title)")
let count = 0...10
for i in count {
publicChargerTitle.append(decodedData[i].AddressInfo.Title)
publicChargerLatitude.append(decodedData[i].AddressInfo.Latitude)
publicChargerLongitude.append(decodedData[i].AddressInfo.Longitude)
publicChargerStatus1.append(decodedData[i].Connections[0].StatusTypeID)
publicChargerStatus2.append(decodedData[i].Connections[1].StatusTypeID)
publicChargerConnector1.append(decodedData[i].Connections[0].ConnectionTypeID)
publicChargerConnector2.append(decodedData[i].Connections[1].ConnectionTypeID)
publicChargerKW1.append(decodedData[i].Connections[0].PowerKW)
publicChargerKW2.append(decodedData[i].Connections[1].PowerKW)
}
This works and adds the data to its own array.
The issue I'm seeing is not all chargers have the same number of connections. So when parsed the arrays are not matching each other at the end. Instead of skipping that array allocation with the next charger data, is there a way I can instead insert Null into the array to hold its place?
I have looked around and haven't yet found a clear solution to this issue. Any help would be greatly appreciated. API data from: https://api.openchargemap.io/
Thanks
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
Below is my returned json from twitter
{
"created_at": "Sat, 11 Feb 2012 06:38:28 +0000",
"entities": {
"hashtags": [
{
"text": "Shubhdin",
"indices": [
9,
18
]
}
],
"urls": [],
"user_mentions": [
{
"screen_name": "SAMdLaw",
"name": "Sabyasachi Mohapatra",
"id": 104420398,
"id_str": "104420398",
"indices": [
0,
8
]
}
]
},
"from_user": "nilayshah80",
"from_user_id": 213599118,
"from_user_id_str": "213599118",
"from_user_name": "Nilay Shah",
"geo": {
"coordinates": [
18.6003,
73.825
],
"type": "Point"
},
"id": 168222351106899968,
"id_str": "168222351106899968",
"iso_language_code": "in",
"metadata": {
"result_type": "recent"
},
"profile_image_url": "http://a2.twimg.com/profile_images/1528184590/IMG_0465_normal.JPG",
"profile_image_url_https": "https://si0.twimg.com/profile_images/1528184590/IMG_0465_normal.JPG",
"source": "<a href="http://twabbit.wordpress.com/" rel="nofollow">twabbit</a>",
"text": "#SAMdLaw #Shubhdin mitra",
"to_user": "SAMdLaw",
"to_user_id": 104420398,
"to_user_id_str": "104420398",
"to_user_name": "Sabyasachi Mohapatra",
"in_reply_to_status_id": 168219865197461505,
"in_reply_to_status_id_str": "168219865197461505"
},
{
"created_at": "Sun, 12 Feb 2012 01:54:07 +0000",
"entities": {
"hashtags": [
{
"text": "IWIllAlwaysLoveYou",
"indices": [
88,
107
]
}
],
"urls": [],
"user_mentions": [],
"media": [
{
"id": 168513175187238912,
"id_str": "168513175187238912",
"indices": [
108,
128
],
"media_url": "http://p.twimg.com/Alat1wsCMAAh-wE.jpg",
"media_url_https": "https://p.twimg.com/Alat1wsCMAAh-wE.jpg",
"url": "http://shortener.twitter.com/dRc4dXH3",
"display_url": "pic.twitter.com/dRc4dXH3",
"expanded_url": "http://twitter.com/RIPWhitneyH/status/168513175183044608/photo/1",
"type": "photo",
"sizes": {
"orig": {
"w": 395,
"h": 594,
"resize": "fit"
},
"large": {
"w": 395,
"h": 594,
"resize": "fit"
},
"thumb": {
"w": 150,
"h": 150,
"resize": "crop"
},
"small": {
"w": 340,
"h": 511,
"resize": "fit"
},
"medium": {
"w": 395,
"h": 594,
"resize": "fit"
}
}
}
]
},
"from_user": "RIPWhitneyH",
"from_user_id": 19319043,
"from_user_id_str": "19319043",
"from_user_name": "RIP Whitney Houston",
"geo": null,
"id": 168513175183044608,
"id_str": "168513175183044608",
"iso_language_code": "en",
"metadata": {
"recent_retweets": 8,
"result_type": "popular"
},
"profile_image_url": "http://a2.twimg.com/profile_images/1820957590/images__13__normal.jpg",
"profile_image_url_https": "https://si0.twimg.com/profile_images/1820957590/images__13__normal.jpg",
"source": "<a href="http://twitter.com/">web</a>",
"text": "R-T if you think that the Grammy's should organize an \"R.I.P. Whitney Houston\" tribute. #IWIllAlwaysLoveYou http://shortener.twitter.com/dRc4dXH3",
"to_user": null,
"to_user_id": null,
"to_user_id_str": null,
"to_user_name": null
},
If you noticed Media under entities not available in above 2 and when i tried to call below snippet gives me null reference error
MediaUrl = (from user in tweet["entities"]["media"]
select new mediaUrl
{
shortUrl = (string)user["url"],
longUrl = (string)user["expanded_url"],
url = (string)user["media_url"],
start = user["indices"][0].ToString(),
end = user["indices"][1].ToString(),
mediaType = (string)user["type"],
}).ToList()
Same code work for Entities/URL, Hashtags and mentions but not for Media.
Also tried this -> Get JSON object node but still getting null reference exception.
In first tweet, entities object doesn't have media property, so when evaluating first tweet, your code would be equivalent to :
MediaUrl = (from user in (IEnumerable<JToken>)null
select new mediaUrl
{
shortUrl = (string)user["url"],
longUrl = (string)user["expanded_url"],
url = (string)user["media_url"],
start = user["indices"][0].ToString(),
end = user["indices"][1].ToString(),
mediaType = (string)user["type"],
}).ToList()
which will throw ArgumentNullException because that code does query on null reference collection.
Finally got working. Not appropriate solution but works for me.
I created separate method for parsing Media. Passed Entity as string and in that method i checked is EntityString.Contains Media or not. If yes, then parse media json else returned null. See below Snippet.
if (Entities != string.Empty)
{
if (Entities.Contains("\"media\":"))
{
JObject searchResult = JObject.Parse(Entities);
returnMedia = (from user in searchResult["media"]
select new mediaUrl
{
shortUrl = (string)user["url"],
longUrl = (string)user["expanded_url"],
url = (string)user["media_url"],
start = user["indices"][0].ToString(),
end = user["indices"][1].ToString(),
mediaType = (string)user["type"],
}).ToList();
}
}
This works for me. If you have any better solution then Please let me know.