Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel: get percentage of each values in array

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

like image 513
Nenad M Avatar asked Dec 05 '25 16:12

Nenad M


2 Answers

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);
like image 52
Sohel0415 Avatar answered Dec 08 '25 06:12

Sohel0415


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,

  1. Union
  2. Equality
  3. Identity
  4. Inequality
  5. Non-Identity

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.

like image 35
Sagar Gautam Avatar answered Dec 08 '25 04:12

Sagar Gautam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!