Laravel: 获取数组中每个值的百分比
Laravel: get percentage of each values in array
我有两个带数字的数组变量。我需要第三个也将是一个数组,但具有前两个数组的百分比。例如:
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);
显示错误不支持的操作数类型
您可以 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);
根据 php
中可用的数组运算符文档
http://php.net/manual/en/language.operators.array.php,
您只能在数组中使用以下运算符,
- 联盟
- 平等
- 身份
- 不平等
- 非身份
对于你的情况,你可以这样做,
如果你有像 $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
数组作为你想要的结果。
我有两个带数字的数组变量。我需要第三个也将是一个数组,但具有前两个数组的百分比。例如:
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);
显示错误不支持的操作数类型
您可以 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);
根据 php
中可用的数组运算符文档http://php.net/manual/en/language.operators.array.php,
您只能在数组中使用以下运算符,
- 联盟
- 平等
- 身份
- 不平等
- 非身份
对于你的情况,你可以这样做,
如果你有像 $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
数组作为你想要的结果。