Sum collection variables - laravel

i have the next collection:
It is grouped by zone and fundo and I need to sum all the sup_ha that each fundo contains
$transporFundo = $tansporCollect->groupBy(['zona','fundo']);
foreach ($transporFundo as $fundo) {
$supFundo = $fundo->sum('sup_ha');
dd($supFundo);
}
that is to say that for example of my collection for zona 1 and fundo 805 I would have to add the sup_ha field of the 364 records that are seen.
I tried to do it but I don't know how to access the field, as seen in my code I tried and it returns 0.
I hope you can help me, thanks
**
UPDATE
**
ok, remove the group by, for example show a collection like the following, the original has 700k of records
Illuminate\Support\Collection {#778646 ▼
#items: array:4 [▼
0 => array:3 [▼
"zona" => 1
"sup_ha" => 20
"fundo" => 805
]
1 => array:3 [▼
"zona" => 1
"sup_ha" => 10
"fundo" => 805
]
2 => array:3 [▼
"zona" => 2
"sup_ha" => 5
"fundo" => 800
]
3 => array:3 [▼
"zona" => 2
"sup_ha" => 10
"fundo" => 900
]
]
}
so, I need the sum of the sup_ha of equal fundo, like this:
fundo | sum
805 | 30
800 | 5
900 | 10
And I need the sum of the sup_ha of equal zona, like this:
zona | sum
1 | 30
2 | 15
Given this, that's why I had made a group by to calculate the sum of the fundo's. so now I don't know whether to think if it was right to do it like this
I hope you have clarified

Assuming your collection is assigned as $collection
$zonaArray = [];
$fundoArray = [];
$sum = 0;
foreach ($collection as $key => $t) {
if (!in_array($t['zona'], $zonaArray)) {
$zonaArray[$key]['zona'] = $t['zona'];
$zonaArray[$key]['sum'] = (float) $t['sup_ha'];
} else {
$zonaArray[$key]['sum'] = (float) $t['sup_ha'];
}
if (!in_array($t['fundo'], $fundoArray)) {
$fundoArray[$key]['fundo'] = $t['fundo'];
$fundoArray[$key]['sum'] = (float) $t['sup_ha'];
} else {
$fundoArray[$key]['sum'] = (float) $t['sup_ha'];
}
}
$checkzona = [];
$value = 0;
$finalZone = [];
$i = 0;
foreach ($zonaArray as $key => $val) {
if (in_array($val['zona'], $checkzona)) {
unset($finalZone[$i - 1]);
$val['sum'] = $value + (float) $val['sum'];
$finalZone[$i] = $val;
$i++;
} else {
$checkzona[] = $val['zona'];
$value = $val['sum'];
$finalZone[$i] = $val;
$i++;
}
}
Your zone wise sum output is looking like below.
array:2 [▼
1 => array:2 [▼
"zona" => 1
"sum" => 30.0
]
3 => array:2 [▼
"zona" => 2
"sum" => 15.0
]
]
For fundo sum:
$checkfundo = [];
$valuefundo = 0;
$finalFundo = [];
$k = 0;
foreach ($fundoArray as $key => $fundo) {
if (in_array($fundo['fundo'], $checkfundo)) {
unset($finalFundo[$k - 1]);
$fundo['sum'] = $valuefundo + (float) $fundo['sum'];
$finalFundo[$k] = $fundo;
$k++;
} else {
$checkfundo[] = $fundo['fundo'];
$valuefundo = $fundo['sum'];
$finalFundo[$k] = $fundo;
$k++;
}
}
Your fundo wise sum output is looking like below.
array:3 [▼
1 => array:2 [▼
"fundo" => 805
"sum" => 30.0
]
2 => array:2 [▼
"fundo" => 800
"sum" => 5.0
]
3 => array:2 [▼
"fundo" => 900
"sum" => 10.0
]
]
I hope it's working for you.

Assuming your collection is assigned to $collection.
so, I need the sum of the sup_ha of equal fundo.
High order functions
return $collection->groupBy('fundo')->map->sum('sup_ha');
Alternative
return $collection
->groupBy('fundo')
->transform(function (Collection $sub) {
return $sub->sum('sup_ha');
});
It prints
{
"805": 30,
"800": 5,
"900": 10
}
And I need the sum of the sup_ha of equal zona
High order functions
return $collection->groupBy('zona')->map->sum('sup_ha');
Alternative
return $collection
->groupBy('zona')
->transform(function (Collection $sub) {
return $sub->sum('sup_ha');
});
It prints
{
"1": 30,
"2": 15
}

Related

laravel controller form array value compere if same pass 1 not pass 0

I'm new to laravel I was trying to get value IN controller form array value compere all "ANSWER" AND "OPTION" array value.
EXAMPLE
ANSWER AND OPTION if
ANSWER 0=>A EQUELS OPTION=>A pass 1
ANSWER 0=>B EQUELS OPTION=>A pass 0
THIS VALUE STORE IN ANSWER_STATUS COLUMANE
CONTROLLER
public function Store_Answer(Request $request)
{
$count= $request->Question;
if ($count) {
for ($i=0; $i <count($request->Question); $i++) {
$data = New OnlineExminAnswer();
$data->ANSWER_STATUS= $request->ANSWER_STATUS; // HERE I WANT TO GET VALUE OF COMPARED 1 OR 0
$data->question = $request->Question [$i];
$data->answer = $request->OPTION[$i];
$data->save();
}
}
my form array
"Question" => array:2 [▼
0 => "YOUR NAME"
1 => "water formula in science"
]
"ANSWER" => array:2 [▼ //THIS ARRAY CONTAINING ALL RIGHT ANSWER
0 => "A"
1 => "h2O"
]
"OPTION" => array:2 [▼ //THIS ARRAY STUDENTS ANSWER
0 => "A"
1 => "CO2"
]
]
public function Store_Answer(Request $request)
{
$count = $request->Question;
if ($count) {
for ($i = 0; $i < count($request->Question); $i++) {
if(isset($request->ANSWER[$i]) && isset($request->OPTION[$i])) {
$data = new OnlineExminAnswer();
$data->ANSWER_STATUS = $request->ANSWER[$i] == $request->OPTION[$i] ? 1 : 0;
$data->question = $request->Question[$i];
$data->answer = $request->OPTION[$i];
$data->save();
}
}
}
}

stream_get_contents in loop work half the time

In my controller I retrieve several boxes, and for the images of each box I do like this because I have the images in a blob column:
$donnees = $entityManager
->getRepository(Occasion::class)
->findBy(['isOnLine' => true], ['id' => "DESC"]);
$occasions = $paginator->paginate(
$donnees, /* query NOT result */
$request->query->getInt('page', 1), /*page number*/
12 /*limit per page*/
);
//on va stocker les images
$images = [];
foreach($occasions as $key => $occasion) {
$images[$key] = stream_get_contents($occasion->getBoite()->getImageBlob());
}
But when I dump $images I only have 1 image out of 2...
CataloguesController.php on line 137:
array:4 [▼
0 => "/9j/4AAQSkZJRgABAQEASABIAAD/2wBDAAIBAQIBAQICAgICAgICAwUDAwMDAwYEBAMFBwYHBwcGBwcICQsJCAgKCAcHCg0KCgsMDAwMBwkODw0MDgsMDAz/2wBDAQICAgMDAwYDAwYMCAcIDAwMDAwMDAwMDAwM ▶"
1 => ""
2 => "/9j/4AAQSkZJRgABAQEAeAB4AAD/2wBDAAIBAQIBAQICAgICAgICAwUDAwMDAwYEBAMFBwYHBwcGBwcICQsJCAgKCAcHCg0KCgsMDAwMBwkODw0MDgsMDAz/2wBDAQICAgMDAwYDAwYMCAcIDAwMDAwMDAwMDAwM ▶"
3 => ""
]
Do you know why ? Thanks
???

foreach count only one result in form

I have this foreach
foreach ($categoryArr as $key => $value) {
foreach ($biciCorretta as $chiave => $valore) {
$biciSingola = $valore;
$contatoreqty =1;
if ($biciSingola->category_id = $key && $contatoreqty <= $value) {
if (!in_array($biciSingola,$biciSelezionata, true)) {
array_push($biciSelezionata, $biciSingola);
}
$contatoreqty ++;
}
}
echo "$contatoreqty <br>";
}
this is dd $categoryAarr:
array:1 [▼
1 => "1"
]
to be precise
array:1 [▼
1(category id) => "1"(quantity request)
]
this is the dd of $biciCorretta (are the bikes I have in that category):
array:2 [▼
0 => App\Models\Bike {#1461 ▶}
1 => App\Models\Bike {#1459 ▶}
]
if the category of the single bike is correct and the quantity ($ value) is less than or equal to the counter
push the bike into the array.
I expect there is only one bike in the $biciSelezionata array as the quantity required is only one
instead the result is the following:
array:2 [▼
0 => App\Models\Bike {#1461 ▶}
1 => App\Models\Bike {#1459 ▶}
]
there is a problem on your condition
if ($biciSingola->category_id = $key && $contatoreqty <= $value) {
The condition here must be ==
Write if ($biciSingola->category_id == $key && $contatoreqty <= $value) { instead
And its important where you initiate your $contatoreqty variable.
it will always be 1 if condition fails

laravel collection groupBy() / include empty results

For a chart API I would need to provide the count of registered users per day.
//fetch all created_at dates of users from the last week
$signUpsLastWeek = User::whereDate('created_at', '>=', now()->subDays(7))->select('created_at')->get();
//group them now by date now, using collection operations
dd($signUpsLastWeek->groupBy(function($item) {
return $item->created_at->format('m.d');
}));
//now manipulate the collection a bit, so we get the date with the amount of new registered users
$signUpsLastWeek->mapWithKeys(function ($userGroup, $key) {
return [$key => $userGroup->count()];
})
Returns:
Illuminate\Database\Eloquent\Collection {#774 ▼
#items: array:1 [▼
"01.19" => 4
]
}
This works fine, a question is left.
In the example code above there are 0 new signups on the other days, meaning the collection should look something like:
Illuminate\Database\Eloquent\Collection {#774 ▼
#items: array:1 [▼
"01.25" => 0,
"01.24" => 0,
"01.23" => 0,
"01.22" => 0,
"01.20" => 0,
"01.19" => 4,
...,
]
}
Any idea how to include the 0 amounts too?
I think you can use CarbonPeriod to create the calendar and set the default count 0 for every date.
And then reset the value from your users' count:
$start_date = explode(' ', User::whereDate('created_at', '>=', now()->subDays(7))->min('created_at'))[0];
$end_date = \Carbon\Carbon::now()->format('Y-m-d');
$period = \Carbon\CarbonPeriod::create($start_date, $end_date);
$all_dates = [];
foreach ($period as $date) {
$all_dates = array_merge($all_dates, [$date->format('m.d') => 0]);
}
$all_dates = array_reverse($all_dates);
collect($all_dates)->mapWithKeys(function($v, $date) use ($signUpsLastWeek) {
if (in_array($date, array_keys($signUpsLastWeek))) {
return [$date => $signUpsLastWeek[$date]->count()];
} else {
return [$date => 0];
}
})->all();

Instead an element in a Laravel Colletion each 3 elements

I have a collection with 4 Object :
Collection{#645 ▼
#items: array:4 [▼
0 => Team {#644 ▶}
1 => Team {#613 ▶}
2 => Team {#607 ▶}
3 => Team {#599 ▶}
]
}
I would like to insert a element each 3, begining by 0 index ( In this case, it would be in 0, and 3)
How should I do it???
The push method doesn't allow me to insert between to elements....
Use the map() helper. I've tested this and it works perfectly:
$counter = 0;
$collection->map(function($i) use(&$counter) {
if ($counter % 3 === 0) {
$i->custom = 'Custom value';
}
$counter++;
return $i;
});

Resources