sum of data in array and add the same sum in same array at bottom - laravel

I am self leaner and stuck at getting the sum of array which i am getting.
Ref. attached image showing the array.
for Month of Aug.
"Aug-2022" => array:6 [▼
"annualbuffalomilksalerecordforcustomer" => "8.00"
"annuala2milksalerecordforcustomer" => "5.50"
"annualjerseymilksalerecordforcustomer" => "2.50"
"annualbuffalomilksalerecord" => "168.00"
"annuala2milksalerecord" => "0.00"
"annualjerseymilksalerecord" => "390.00"
Here i want the sum all 6 which is = 574.00
expected result is -
"Aug-2022" => array:6 [▼
"annualbuffalomilksalerecordforcustomer" => "8.00"
"annuala2milksalerecordforcustomer" => "5.50"
"annualjerseymilksalerecordforcustomer" => "2.50"
"annualbuffalomilksalerecord" => "168.00"
"annuala2milksalerecord" => "0.00"
"annualjerseymilksalerecord" => "390.00"
"sumofmilksale" => "574.00"

You could do it like this using the map() function :
$collection = collect([
'Apr-2022' => [
"annualbuffalomilksalerecordforcustomer" => "8.00",
"annuala2milksalerecordforcustomer" => "5.50",
"annualjerseymilksalerecordforcustomer" => "2.50",
"annualbuffalomilksalerecord" => "168.00",
"annuala2milksalerecord" => "0.00",
"annualjerseymilksalerecord" => "390.00",
],
'May-2022' => [
"annualbuffalomilksalerecordforcustomer" => "8.00",
"annuala2milksalerecordforcustomer" => "5.50",
"annualjerseymilksalerecordforcustomer" => "2.50",
"annualbuffalomilksalerecord" => "168.00",
"annuala2milksalerecord" => "0.00",
"annualjerseymilksalerecord" => "390.00",
],
]);
$mapped = $collection->map(function ($entry) {
$sum = array_sum($entry);
return array_merge($entry, ['sumofmilksale' => $sum]);
})
dd($mapped);

Related

Create a collection given a number of times keeping the key

I'm trying to create a kind of dataset using laravel Collections, for this I'm using the "times" method:
function getValidData(int $amount): Collection
{
return Collection::times($amount, function (int $number): array {
$password = faker()->password(8, 12);
return [
"User #{$number}" => [
'name' => faker()->firstName(),
'email' => faker()->unique()->safeEmail(),
'password' => $password,
'password_confirmation' => $password
]
];
});
}
However, the result is not as I expected:
[
0 => [
'User #1' => [
'name' => 'ana',
'email' => 'ana#email.com',
'password' => '12345678',
'password_confirmation' => '12345678'
]
],
1 => [
'User #2' => [
'name' => 'leo',
'email' => 'leo#email.com',
'password' => '3231232132',
'password_confirmation' => '3231232132'
]
]
]
I was hoping it would be:
[
'User #1' => [
'name' => 'ana',
'email' => 'ana#email.com',
'password' => '12345678',
'password_confirmation' => '12345678'
],
'User #2' => [
'name' => 'leo',
'email' => 'leo#email.com',
'password' => '3231232132',
'password_confirmation' => '3231232132'
]
]
I can solve this using array_merge(...(Collection::times...)) but it seems a kinda off... Is there any way to solve this in a cleaner way using Collections?
If you would like to map the collection with new keys, you could do the following, using the mapWithKeys() function.
Example
$users = collect(range(1, $amount))
->mapWithKeys( function($index) {
$password = faker()->password(8, 12);
return [sprintf("User #%d", $index) => [
'name' => faker()->firstName(),
'email' => faker()->unique()->safeEmail(),
'password' => $password,
'password_confirmation' => $password,
]];
});
This will run from 1 to the specified $amount. Example output with 3 users:
Illuminate\Support\Collection {#2016
#items: array:3 [
"User #1" => array:4 [
"name" => "Garret"
"email" => "aurelio03#example.com"
"password" => "Vp=Et3!?w0"
"password_confirmation" => "Vp=Et3!?w0"
]
"User #2" => array:4 [
"name" => "Genoveva"
"email" => "hilda.bins#example.net"
"password" => "W?miL1Kts"
"password_confirmation" => "W?miL1Kts"
]
"User #3" => array:4 [
"name" => "Zella"
"email" => "mmurray#example.net"
"password" => "g8)"pYgjQ~"
"password_confirmation" => "g8)"pYgjQ~"
]
]
}
You could also chain the toArray() method on the collection if you prefer an Array over a Collection.

Remove duplicates in Laravel collection only if previous item is identical

I have a Laravel Collection of items:
[
[
'id' => 1,
'path' => '/',
'created_at' => '2020-05-20 20:12:00'
],
[
'id' => 2,
'path' => '/somewhere',
'created_at' => '2020-05-20 21:01:00'
],
[
'id' => 3,
'path' => '/somewhere',
'created_at' => '2020-05-20 21:21:00'
],
[
'id' => 4,
'path' => '/somewhere/else',
'created_at' => '2020-05-20 21:09:00'
],
[
'id' => 5,
'path' => '/somewhere/else',
'created_at' => '2020-05-20 21:10:00'
],
]
This is the raw data that would be found in the collection if I cast it to an array, but I need it to remain in collection format.
I need to remove any duplicates where the current item has the same path and is less than 5 minutes old compared to the previous item.
So in this case, item #4 would be removed leaving only #5, but items #2 and #3 would be kept even tho their paths are the same.
How would I do this?
Use the following namespace in your controller file:
use DateTime;
Use the following code in your controller file:
$collection = [
[
'id' => 1,
'path' => '/',
'created_at' => '2020-05-20 20:12:00'
],
[
'id' => 2,
'path' => '/somewhere',
'created_at' => '2020-05-20 21:01:00'
],
[
'id' => 3,
'path' => '/somewhere',
'created_at' => '2020-05-20 21:21:00'
],
[
'id' => 4,
'path' => '/somewhere/else',
'created_at' => '2020-05-20 21:09:00'
],
[
'id' => 5,
'path' => '/somewhere/else',
'created_at' => '2020-05-20 21:10:00'
],
];
$paths = [];
$time_count = [];
foreach ($collection as $key => $data) {
if (in_array($data['path'], $paths)) {
$arr_pos = array_search($data['path'], array_values($paths));
$datetime1 = new DateTime($data['created_at']);
$datetime2 = new DateTime($collection[$arr_pos]['created_at']);
$interval = $datetime1->diff($datetime2);
$mins = $interval->format('%i');
if ($mins < 5) {
unset($collection[$arr_pos]);
}
}
$paths[] = $data['path'];
}
This will return result:
array:4 [▼
0 => array:3 [▼
"id" => 1
"path" => "/"
"created_at" => "2020-05-20 20:12:00"
]
1 => array:3 [▼
"id" => 2
"path" => "/somewhere"
"created_at" => "2020-05-20 21:01:00"
]
2 => array:3 [▼
"id" => 3
"path" => "/somewhere"
"created_at" => "2020-05-20 21:21:00"
]
4 => array:3 [▼
"id" => 5
"path" => "/somewhere/else"
"created_at" => "2020-05-20 21:10:00"
]
]
I hope this works for you.

If condition with array in Laravel

I'm trying to create an array to convert JSON. My data is queried from database.
My problem is I have to check condition for array. If $item->verified == 1, my 'isVerified'
will be true, my email will be in verified and opposite.
Here is what I did, I check condition and create 2 array for it. Can I just use 1 array
for condition:
if( ($item->verified) == 1)
{
$data[] = [
'name' => $item->fullname,
'address' => $item->address,
'isVerified' => true,
'email' => [
'verified' => $item->email,
'unverified' => []
]
];
}
else
{
$data[] = [
'name' => $item->fullname,
'address' => $item->address,
'isVerified' => false,
'email' => [
'verified' => [],
'unverified' => $item->email
]
];
}
You can use ternary operator.
$data[] = [
'name' => $item->fullname,
'address' => $item->address,
'isVerified' => $item->verified == 1,
'email' => [
'verified' => $item->verified == 1 ? $item->email : [],
'unverified' => $item->verified == 0 ? $item->email : [],
]
];

How to Combine Aggregate + Lookup and Search in Laravel

I Have the following Aggregate + Lookup Query
Aggregate + lookup Query
$collection = Dapil_Kotakab::raw(function ($collection) use ($page, $perPage) {
return $collection->aggregate([
[
'$lookup' => [
'as' => 'KecDetails',
'from' => 'src_kecamatan',
'foreignField' => 'id',
'localField' => 'idKecamatan'
]
],
[
'$lookup' => [
'as' => 'KotDetails',
'from' => 'src_kota_kabupaten',
'foreignField' => 'code',
'localField' => 'idKota'
]
],
[
'$lookup' => [
'as' => 'ProvDetails',
'from' => 'src_provinsi',
'foreignField' => 'idProv',
'localField' => 'idProvinsi'
]
],
['$skip' => ($page - 1) * $perPage],
['$limit' => $perPage],
]);
});
And I have the following $Search code.
$collection = Dapil_Kotakab::whereRaw(array('$text'=>array('$search'=> "\"".$word."\"" )))->skip(($page - 1)*$perPage)->limit($perPage)->get();
I have tried several times, But I keep getting error.
Any suggestions in this regard will be appreciated.

Change SKU column value in collection with map

I have an object :
array:100 [▼
0 => array:62 [▼
"id" => 9407
"name" => "Gramophone (El)"
"slug" => "gramophone-el"
"permalink" => "https://wordpress.dev/index.php/produit/gramophone-el/"
"date_created" => "2016-12-23T16:57:13"
"date_modified" => "2016-12-23T23:10:40"
"type" => "variable"
"status" => "publish"
"featured" => false
"catalog_visibility" => "visible"
"description" => "<p>Des magistrats au tribunal écoutent parler un Gramophone en cours d'audience.</p>\n"
"short_description" => ""
"sku" => 1900123Z0
"price" => ""
"regular_price" => ""
"sale_price" => ""
"date_on_sale_from" => ""
"date_on_sale_to" => ""
"price_html" => ""
"on_sale" => false
"purchasable" => false
"total_sales" => 0
"virtual" => false
"downloadable" => false
"downloads" => []
"download_limit" => -1
"download_expiry" => -1
"download_type" => "standard"
"external_url" => ""
"button_text" => ""
"tax_status" => "taxable"
"tax_class" => ""
"manage_stock" => false
"stock_quantity" => null
"in_stock" => false
"backorders" => "no"
"backorders_allowed" => false
"backordered" => false
"sold_individually" => false
"weight" => ""
"dimensions" => array:3 [ …3]
"shipping_required" => true
"shipping_taxable" => true
"shipping_class" => ""
"shipping_class_id" => 0
"reviews_allowed" => true
"average_rating" => "0.00"
"rating_count" => 0
"related_ids" => array:5 [ …5]
"upsell_ids" => []
"cross_sell_ids" => []
"parent_id" => 0
"purchase_note" => ""
"categories" => array:1 [ …1]
"tags" => array:1 [ …1]
"images" => array:1 [ …1]
"attributes" => array:7 [ …7]
"default_attributes" => []
"variations" => []
"grouped_products" => []
"menu_order" => 0
"_links" => array:2 [ …2]
]
$products->map(function($item){
return $item['sku'] = substr($item['sku'], 0, 7);
})->groupBy('sku');
What I need is to keep the first 7 characters of SKU Field, and group my collection by SKU.
Thing is as I do it, sku is never modified.... What is my error????
You can't do it since groupBy on collection works on sql level, it will alter the query to get the result for you.
What you need is
$groupByProducts = $products->groupBy(DB::raw('substr(sku, 0, 7)'));

Resources