I'm trying to do some data transformation through Laravel collection in my application for graphs. I want to create labels and datasets
I'm having a data something like this:
[
{
"id": 1,
"company_id": 1,
"year": 25,
"turnover": "3449",
"profit": "3201",
"turnover_range": 25,
"financial_year": {
"id": 25,
"year": "2024-25"
}
},
{
"id": 2,
"company_id": 1,
"year": 33,
"turnover": "5616",
"profit": "5905",
"turnover_range": 25,
"financial_year": {
"id": 33,
"year": "2032-33"
}
},
{
"id": 3,
"company_id": 1,
"year": 1,
"turnover": "4309",
"profit": "8563",
"turnover_range": 175,
"financial_year": {
"id": 1,
"year": "2000-01"
}
},
{
"id": 4,
"company_id": 1,
"year": 14,
"turnover": "5936",
"profit": "8605",
"turnover_range": 25,
"financial_year": {
"id": 14,
"year": "2013-14"
}
},
{
"id": 5,
"company_id": 1,
"year": 29,
"turnover": "7156",
"profit": "3844",
"turnover_range": 75,
"financial_year": {
"id": 29,
"year": "2028-29"
}
},
{
"id": 6,
"company_id": 1,
"year": 6,
"turnover": "5868",
"profit": "633",
"turnover_range": 75,
"financial_year": {
"id": 6,
"year": "2005-06"
}
},
{
"id": 7,
"company_id": 1,
"year": 25,
"turnover": "5809",
"profit": "6831",
"turnover_range": 575,
"financial_year": {
"id": 25,
"year": "2024-25"
}
},
{
"id": 8,
"company_id": 1,
"year": 12,
"turnover": "1",
"profit": "1976",
"turnover_range": 25,
"financial_year": {
"id": 12,
"year": "2011-12"
}
},
{
"id": 9,
"company_id": 1,
"year": 30,
"turnover": "680",
"profit": "1222",
"turnover_range": 25,
"financial_year": {
"id": 30,
"year": "2029-30"
}
},
{
"id": 10,
"company_id": 1,
"year": 26,
"turnover": "8197",
"profit": "3687",
"turnover_range": 25,
"financial_year": {
"id": 26,
"year": "2025-26"
}
}
]
Which is coming from eloquent collection of my model:
$fRA = FinancialAndRisk::whereHas('company', function($q) use($request){
$q->where('slug', $request->slug);
})
->with('financialYear')
->get();
I want to pluck out all the year inside financial_year as labels so i tried:
$labels = $fRA->pluck('financial_year.year');
it is showing null.
Again I tried
$labels= $fRA->map(function ($item){
$item->fin_year = $item->financial_year['year'];
return $item;
})->pluck('fin_year');
Even if I do transform I am getting the same null result,
Any ideas appreciated. Thanks
Edit:
Data format to be something like this:
labels = ['2000-01','2032-33','2024-25','2005-06'];
You should just be able to do something like:
$labels = $fRA->map(function ($item) {
return $item->financial_year->year;
})->unique();
Obviously, remove unique() if you want to include the duplicates (if there are any).
Alternatively, if you have the hasMany relationship set up in your FinancialYear model and you don't need $fRA after this you could just do:
$labels = FinancialYear::whereHas('FinancialAndRisk.company', function ($query) use($request) {
$query->where('slug', $request->slug);
})->pluck('year');
Related
I have an response with this structure.
{
"records": [
{
"patientName": "CECILIA NONE ANCINEZ DE LOPEZ",
"patientProductCode": "MO000250",
"patientProduct": "RUXOLITINIB 15 MG TABLETA",
"patientFirstDispatch": "18/11/2021",
"dispatch": [
{
"month": 6,
"year": 2022,
"quantity": 30,
"period": "2022-6"
},
{
"month": 4,
"year": 2022,
"quantity": 30,
"period": "2022-4"
},
{
"month": 3,
"year": 2022,
"quantity": 30,
"period": "2022-3"
},
{
"month": 2,
"year": 2022,
"quantity": 30,
"period": "2022-2"
},
{
"month": 1,
"year": 2022,
"quantity": 30,
"period": "2022-1"
},
{
"month": 12,
"year": 2021,
"quantity": 30,
"period": "2021-12"
}
]
},
]
}
and I also have this json with the last 7 months.
{
"months": [
{
"month": "June",
"position": 6,
"year": 2022,
"period": "2022-6"
},
{
"month": "May",
"position": 5,
"year": 2022,
"period": "2022-5"
},
{
"month": "April",
"position": 4,
"year": 2022,
"period": "2022-4"
},
{
"month": "March",
"position": 3,
"year": 2022,
"period": "2022-3"
},
{
"month": "February",
"position": 2,
"year": 2022,
"period": "2022-2"
},
{
"month": "January",
"position": 1,
"year": 2022,
"period": "2022-1"
},
{
"month": "December",
"position": 12,
"year": 2021,
"period": "2021-12"
}
]
}
I need to add an object inside the dispatch array with the property
"quantity" = 0 when the "period" property doesn't match between the dispatch array and the months array.
the result of comparing between the array "months" and "dispatch" should return something like this.
An object was added at position 1 of the "dispatch" array.
{
"records": [
{
"patientName": "CECILIA NONE ANCINEZ DE LOPEZ",
"patientProductCode": "MO000250",
"patientProduct": "RUXOLITINIB 15 MG TABLETA",
"patientFirstDispatch": "18/11/2021",
"dispatch": [
{
"month": 6,
"year": 2022,
"quantity": 30,
"period": "2022-6"
},
{
"month": 5,
"year": 2022,
"quantity": 0,
"period": "2022-5"
},
{
"month": 4,
"year": 2022,
"quantity": 30,
"period": "2022-4"
},
{
"month": 3,
"year": 2022,
"quantity": 30,
"period": "2022-3"
},
{
"month": 2,
"year": 2022,
"quantity": 30,
"period": "2022-2"
},
{
"month": 1,
"year": 2022,
"quantity": 30,
"period": "2022-1"
},
{
"month": 12,
"year": 2021,
"quantity": 30,
"period": "2021-12"
}
]
},
]
}
I tried to do it but I could not add the objects correctly.
could you help me with this problem.
You can use forEach() and array_filter() for searching, then add new record to dispatch. Same as :
foreach ($objectMonths->months as $arrayMonth) {
foreach ($objectDispatch->records as $record) {
$exist = array_filter($record->dispatch, fn($mon) => $mon->period === $arrayMonth->period);
if (!count($exist)) {
$month = date('m', strtotime($arrayMonth->period));
$record->dispatch[] = (object)['month' => (int)$month, 'year' => $arrayMonth->year, 'quantity' => 0, 'period' => $arrayMonth->period];
usort($record->dispatch, fn($a, $b) => $a->period < $b->period);
}
}
}
Code sample in here
I have an array of objects that I need to sort by parent (from lowest to highest).
Here's the structure of the array:
[{
"term_id": 9,
"name": "pve",
"slug": "pve",
"term_group": 0,
"term_taxonomy_id": 9,
"taxonomy": "post_tag",
"description": "pve guides",
"parent": 15,
"count": 0,
"filter": "raw"
}, {
"term_id": 8,
"name": "pvp",
"slug": "pvp",
"term_group": 0,
"term_taxonomy_id": 8,
"taxonomy": "post_tag",
"description": "pvp guides",
"parent": 15,
"count": 2,
"filter": "raw"
}, {
"term_id": 11,
"name": "greataxe",
"slug": "greataxe",
"term_group": 0,
"term_taxonomy_id": 11,
"taxonomy": "post_tag",
"description": "greataxe guides",
"parent": 14,
"count": 1,
"filter": "raw"
}, {
"term_id": 12,
"name": "musket",
"slug": "musket",
"term_group": 0,
"term_taxonomy_id": 12,
"taxonomy": "post_tag",
"description": "musket guides",
"parent": 14,
"count": 0,
"filter": "raw"
}, {
"term_id": 13,
"name": "spear",
"slug": "spear",
"term_group": 0,
"term_taxonomy_id": 13,
"taxonomy": "post_tag",
"description": "",
"parent": 14,
"count": 1,
"filter": "raw"
}, {
"term_id": 10,
"name": "sword",
"slug": "sword",
"term_group": 0,
"term_taxonomy_id": 10,
"taxonomy": "post_tag",
"description": "sword guides",
"parent": 14,
"count": 0,
"filter": "raw"
}, {
"term_id": 15,
"name": "Play Type",
"slug": "playtype",
"term_group": 0,
"term_taxonomy_id": 15,
"taxonomy": "post_tag",
"description": "",
"parent": 0,
"count": 0,
"filter": "raw"
}, {
"term_id": 14,
"name": "Weapons",
"slug": "weapons",
"term_group": 0,
"term_taxonomy_id": 14,
"taxonomy": "post_tag",
"description": "",
"parent": 0,
"count": 0,
"filter": "raw"
}]
I tried sorting it with the follow
$new_array = usort($tags, function($a, $b) {
return $b->parent - $a->parent;
})
My desired outcome would be an array which reorganizes the array by parent (so all the objects with a parent of 0 would be on the top). Instead, I'm getting a value of true returned.
Any help would be appreciated.
usort (http://php.net/usort) performs the sort directly on the provided array. The return value just returns boolean telling if the sorting succeeded.
Furthermore,
The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.
therefore you should provide $a->parent - $b->parent to get the items sorted in an ascending order.
usort($tags, function($a, $b) {
return $a->parent - $b->parent;
});
$new_array = $tags; // The $tags is now sorted
Lumen v 5.7
I have json response like this
{
"data": {
"id": 172,
"name": "Group Test",
"groupmates": [
{
"id": 4555,
"name": "Andri Josua",
"peer_reviews": [
{
"id": 509,
"peer_review_period_id": 17,
"peer_review_setting_id": 15,
"peer_review_setting_item_id": 72,
"student_id": 4555,
"peer_review_setting": {
"id": 15,
"criteria": "Partisipasi",
"partner_id": 6,
"created_at": "2017-07-05T06:44:12.000Z",
"updated_at": "2018-11-28T04:12:37.000Z",
"peer_review_setting_items": [
{
"id": 71,
"peer_review_setting_id": 15,
"partner_id": 6,
"remarks": "Sangat Tidak Baik",
"grade": "0",
"description": "Anggota kelompok,\r\n• tidak berpartisipasi dalam tugas kelompok.\r\n\r\n",
"order_number": 1,
"created_at": "2017-07-05T06:44:12.000Z",
"updated_at": "2017-07-05T06:44:12.000Z"
},
{
"id": 72,
"peer_review_setting_id": 15,
"partner_id": 6,
"remarks": "Tidak Baik",
"grade": "40",
"description": "Anggota kelompok,\r\n • jarang berpartisipasi, • waktu terbuang, atau • mengerjakan materi yang tidak terkait.",
"order_number": 2,
"created_at": "2017-07-05T06:44:12.000Z",
"updated_at": "2017-07-05T06:44:12.000Z"
},
]
}
}
]
}
]
}
}
and controller like this
public function csu($studentId, $klassId, $csuId)
{
$student = Student::findOrFail($studentId);
$contentSectionUnit = ContentSectionUnit::findOrFail($csuId);
$prPeriod = $contentSectionUnit->peer_review_periods->first();
$group = ClassGroup::me($student)
->with(['class_group_students' => function ($query) use ($studentId, $prPeriod) {
$query->with(['peer_reviews' => function ($query) use ($studentId, $prPeriod) {
$query->with(['peer_review_setting' => function ($query) {
$query->with('peer_review_setting_items');
}])
->where('peer_review_period_id', $prPeriod->id)
->where('student_reviewer_id', $studentId)
->orderBy('peer_review_setting_id', 'asc');
}])
->where('student_id', '!=', $studentId)
->orderBy('student_id', 'asc');
}])
->whereKlassId($klassId)
->first();
return new PeerReviewContentResource($group);
}
I want to add new attribute checked in peer_review_setting_items, which value of the attribute is obtained from checking where peer_review_setting_item_id == peer_review_setting_items->id.
How to send peer_review_setting_item_id at peer_review attribute to peer_review_setting_items relation?
Expected result is like this
...
"peer_review_setting_items": [
{
"id": 71,
"peer_review_setting_id": 15,
"partner_id": 6,
"remarks": "Sangat Tidak Baik",
"grade": "0",
"description": "Anggota kelompok,\r\n• tidak berpartisipasi dalam tugas kelompok.\r\n\r\n",
"order_number": 1,
"created_at": "2017-07-05T06:44:12.000Z",
"updated_at": "2017-07-05T06:44:12.000Z",
"checked": false
},
{
"id": 72,
"peer_review_setting_id": 15,
"partner_id": 6,
"remarks": "Tidak Baik",
"grade": "40",
"description": "Anggota kelompok,\r\n • jarang berpartisipasi, • waktu terbuang, atau • mengerjakan materi yang tidak terkait.",
"order_number": 2,
"created_at": "2017-07-05T06:44:12.000Z",
"updated_at": "2017-07-05T06:44:12.000Z",
"checked": true
},
]
...
Laravel custom pagination page 2 result return as object not array.
This is my code of custom pagination
function custom_paginate($data)
{
//Get current page form url e.g. &page=6
$currentPage = LengthAwarePaginator::resolveCurrentPage();
//Create a new Laravel collection from the array data
$collection = new Collection($data);
//Define how many items we want to be visible in each page
$per_page = (int) per_page();
//Slice the collection to get the items to display in current page
$currentPageResults = $collection->slice(($currentPage - 1) * $per_page, $per_page)->all();
//Create our paginator and add it to the data array
$data['results'] = new LengthAwarePaginator($currentPageResults, count($collection), $per_page);
//Set base url for pagination links to follow e.g custom/url?page=6
return $data['results']->setPath(request()->url());
}
when i am at page 1 data is coming as array but in same code if i passed page=2result is coming as object.
Expected result
{
"current_page": 2,
"data": [
{
"_id": 34,
"state": "Andaman & Nicobar Islands",
"post_count": 8,
"totalPhotos": 0,
"totalVideos": 1,
"totalAudios": 0
},
{
"_id": 28,
"state": "Andhra Pradesh",
"post_count": 888,
"totalPhotos": 0,
"totalVideos": 111,
"totalAudios": 0
},
{
"_id": 12,
"state": "Arunachal Pradesh",
"post_count": 200,
"totalPhotos": 0,
"totalVideos": 25,
"totalAudios": 0
},
{
"_id": 18,
"state": "Assam",
"post_count": 464,
"totalPhotos": 0,
"totalVideos": 58,
"totalAudios": 0
},
{
"_id": 10,
"state": "Bihar",
"post_count": 1072,
"totalPhotos": 0,
"totalVideos": 134,
"totalAudios": 0
}
],
"first_page_url": "http://swachh-manch-data.git/insight/posts?page=1",
"from": 6,
"last_page": 8,
"last_page_url": "http://swachh-manch-data.git/insight/posts?page=8",
"next_page_url": "http://swachh-manch-data.git/insight/posts?page=3",
"path": "http://swachh-manch-data.git/insight/posts",
"per_page": 5,
"prev_page_url": "http://swachh-manch-data.git/insight/posts?page=1",
"to": 10,
"total": 36
}
but getting data as object on page 2 (Actual result)
{
"current_page": 2,
"data": {
"5": {
"_id": 4,
"state": "Chandigarh",
"post_count": 8,
"totalPhotos": 0,
"totalVideos": 1,
"totalAudios": 0
},
"6": {
"_id": 22,
"state": "Chhattisgarh",
"post_count": 1336,
"totalPhotos": 0,
"totalVideos": 167,
"totalAudios": 0
},
"7": {
"_id": 26,
"state": "Dadra & Nagar Haveli",
"post_count": 8,
"totalPhotos": 0,
"totalVideos": 1,
"totalAudios": 0
},
"8": {
"_id": 25,
"state": "Daman & Diu",
"post_count": 16,
"totalPhotos": 0,
"totalVideos": 2,
"totalAudios": 0
},
"9": {
"_id": 7,
"state": "Delhi",
"post_count": 40,
"totalPhotos": 0,
"totalVideos": 5,
"totalAudios": 0
}
},
"first_page_url": "http://swachh-manch-data.git/insight/posts?page=1",
"from": 6,
"last_page": 8,
"last_page_url": "http://swachh-manch-data.git/insight/posts?page=8",
"next_page_url": "http://swachh-manch-data.git/insight/posts?page=3",
"path": "http://swachh-manch-data.git/insight/posts",
"per_page": 5,
"prev_page_url": "http://swachh-manch-data.git/insight/posts?page=1",
"to": 10,
"total": 36
}
i am not sure but the problem is in $currentPageResults = $collection->slice(($currentPage - 1) * $per_page, $per_page)->all(); this line.
Thanks in advance. :)
Change
$currentPageResults = $collection->slice(($currentPage - 1) * $per_page, $per_page)->all();
to
$currentPageResults = $collection->slice(($currentPage - 1) * $per_page, $per_page)->values();
for more info read this.
Im having trouble extracting data from a API, i would like to use for a school project..
The link to the API i here
Or here's a sample of the API output
{
"help": "http://www.odaa.dk/api/3/action/help_show?name=datastore_search",
"success": true,
"result": {
"resource_id": "2a82a145-0195-4081-a13c-b0e587e9b89c",
"fields": [
{
"type": "int4",
"id": "_id"
},
{
"type": "text",
"id": "date"
},
{
"type": "text",
"id": "garageCode"
},
{
"type": "int4",
"id": "totalSpaces"
},
{
"type": "int4",
"id": "vehicleCount"
}
],
"records": [
{
"date": "2015/11/11 03:50:07",
"vehicleCount": 62,
"_id": 1,
"totalSpaces": 65,
"garageCode": "NORREPORT"
},
{
"date": "2015/11/11 03:50:07",
"vehicleCount": 512,
"_id": 2,
"totalSpaces": 512,
"garageCode": "SKOLEBAKKEN"
},
{
"date": "2015/11/11 03:50:07",
"vehicleCount": 236,
"_id": 3,
"totalSpaces": 1240,
"garageCode": "SCANDCENTER"
},
{
"date": "2015/11/11 03:50:07",
"vehicleCount": 40,
"_id": 4,
"totalSpaces": 953,
"garageCode": "BRUUNS"
},
{
"date": "2015/11/11 03:50:07",
"vehicleCount": 2932,
"_id": 5,
"totalSpaces": 142,
"garageCode": "BUSGADEHUSET"
},
{
"date": "2015/11/11 03:50:07",
"vehicleCount": 18,
"_id": 6,
"totalSpaces": 383,
"garageCode": "MAGASIN"
},
{
"date": "2015/11/11 03:50:07",
"vehicleCount": 3,
"_id": 7,
"totalSpaces": 210,
"garageCode": "KALKVAERKSVEJ"
},
{
"date": "2015/11/11 03:50:07",
"vehicleCount": 255,
"_id": 8,
"totalSpaces": 700,
"garageCode": "SALLING"
},
{
"date": "2015/11/11 03:50:07",
"vehicleCount": 0,
"_id": 9,
"totalSpaces": 0,
"garageCode": "DOKK1"
},
{
"date": "2015/11/11 03:50:07",
"vehicleCount": 34,
"_id": 10,
"totalSpaces": 449,
"garageCode": "Navitas"
},
{
"date": "2015/11/11 03:50:07",
"vehicleCount": 105,
"_id": 11,
"totalSpaces": 105,
"garageCode": "NewBusgadehuset"
},
{
"date": "2015/11/11 03:50:07",
"vehicleCount": 9,
"_id": 12,
"totalSpaces": 319,
"garageCode": "Urban Level 1"
},
{
"date": "2015/11/11 03:50:07",
"vehicleCount": 15,
"_id": 13,
"totalSpaces": 654,
"garageCode": "Urban Level 2+3"
}
],
"_links": {
"start": "/api/action/datastore_search?resource_id=2a82a145-0195-4081-a13c-b0e587e9b89c",
"next": "/api/action/datastore_search?offset=100&resource_id=2a82a145-0195-4081-a13c-b0e587e9b89c"
},
"total": 13
}
}
I would like to extract the cells called "vehicleCount" and "_id", but i seems I can't figure out how to do it :(
$json = file_get_contents('http://www.odaa.dk/api/action/datastore_search?resource_id=2a82a145-0195-4081-a13c-b0e587e9b89c');
$json = json_decode($json);
echo $json->fields->_id;
I have tried many different ways, but now loss of ideas and its 4 o'clock in the morning, so hopefully someone can help me.
if you want to extract the cells vehicleCount and _id
This is my solution for you:
<?php
$json = file_get_contents('http://www.odaa.dk/api/action/datastore_search?resource_id=2a82a145-0195-4081-a13c-b0e587e9b89c');
$json = json_decode($json);
foreach ($json->result->records as $val) {
echo "_id = " .$val->_id . " vehicleCount = " . $val->vehicleCount . "<br>";
}
?>
$json->result->records[0]->_id