【问题标题】:Laravel: get percentage of each values in arrayLaravel:获取数组中每个值的百分比
【发布时间】:2018-07-12 00:44:31
【问题描述】:

我有两个带有数字的数组变量。我需要第三个,他也将是一个数组,但前两个数组的百分比。例如:

array:15 [▼
  0 => 256
  1 => 312
  2 => 114
]

array:15 [▼
      0 => 100
      1 => 211
      2 => 12
    ]

所以我需要一个看起来像这样的变量:

array:15 [▼
          0 => 39.0
          1 => 67.6
          2 => 10.5
        ]

我得到的前两个变量是这样的:

$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();
}

但是当我尝试这样计算百分比时:

$percentage = round(($sett_m / $sett) * 100,1);

显示错误不支持的操作数类型

【问题讨论】:

  • 你不能直接用两个数组做数学运算,你必须用数组元素做。
  • 如何从数组中分离元素以便进行数学运算?
  • 你能解释一下你的计算吗?
  • 我已添加我的答案,请稍候查看。

标签: arrays laravel percentage


【解决方案1】:

您可以通过您的数组loop,使用same index 元素执行calculation 并存储在new 数组中。

$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);

【讨论】:

  • 如何避免 除以零错误,因为我有一些元素为 0?
  • 检查股息元素是否为零,检查我更新的答案
【解决方案2】:

根据 php 中可用的数组运算符的文档

http://php.net/manual/en/language.operators.array.php,

您只能在数组中使用以下运算符,

  1. 联合
  2. 平等
  3. 身份
  4. 不平等
  5. 非身份

对于你的情况,你可以这样做,

如果你有 $arr1$arr2 这样的数组,那么,

$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);

在这里你会得到$percentage数组作为想要的结果。

【讨论】:

  • 什么是 $arr2?那是 $second 吗?
  • $arr1 是你的第一个数组,arr2 是你的第二个数组
  • 我已经更新了我的答案,以便您轻松理解。任何你理解它是如何工作的方式。我很高兴
猜你喜欢
  • 2020-10-19
  • 1970-01-01
  • 1970-01-01
  • 2018-12-24
  • 1970-01-01
  • 2013-10-03
  • 2019-10-26
  • 1970-01-01
  • 2022-01-17
相关资源
最近更新 更多