I have a two array variables with numbers. I need a third one who will also be an array but with percentage of first two arrays. For example:
array:15 [▼
0 => 256
1 => 312
2 => 114
]
array:15 [▼
0 => 100
1 => 211
2 => 12
]
so I need a variable to look like this:
array:15 [▼
0 => 39.0
1 => 67.6
2 => 10.5
]
The first two variables I get like this:
$settlements = Settlement::where('town_id', Auth::user()->town_id)
->withCount('members')
->where('reon_id', '1')
->get();
foreach ($settlements as $settlement) {
$sett[] = $settlement->members->count();
}
$sett_members = Settlement::where('town_id', Auth::user()->town_id)
->withCount('members')
->where('reon_id', '1')
->get();
foreach ($sett_members as $sett_member) {
$sett_m[] = $sett_member->members->where('cipher_id', '0')->count();
}
but when I try to calculate percentage like this:
$percentage = round(($sett_m / $sett) * 100,1);
it shows error Unsupported operand types
You can loop through your array, do calculation with same index element and store in a new array.
$percentage = array();
for($i=0;$i<count($sett_m);$i++) {
if($sett[$i]!=0){
$percentage[$i] = round(($sett_m[$i] / $sett[$i]) * 100, 1);
}
}
print_r($percentage);
As per documentation of array operators available in php
http://php.net/manual/en/language.operators.array.php,
you can only use following operators in array,
for your case, you can do it like,
if you have arrays like $arr1 and $arr2 then,
$arr1 = array(0 => 256, 1 => 312,2 => 114);
$arr2 = array(0 => 100,1 => 211,2 => 12);
$calculator = function($first, $second) {
if($second == 0)
return 0;
else
return round($first/$second * 100,2);
};
$percentage = array_map($calculator, $arr2, $arr1);
Here you will get $percentage array as the desired result.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With