![](/img/trans.png)
[英]How can I equally divide values in two parts while keeping the total equal for pagination for all possible pages?
[英]How to add all the values of an array and divide by the total number of entries?
我有一個數組$prices = array();
。 該數組包含許多顯示價格的條目。
例如€ 2.500
我的目標是將所有這些值相加並得到平均值。 但首先,要有2500
€ 2.500
格式
這是我所知道的,它是通過使用
preg_replace('/[^0-9]/i', '', $variable);
有什么方法可以做到這一點?
謝謝
您可以使用array_map
將該正則表達式應用於每個元素。
$avg = array_sum(array_map(function($v){
return preg_replace('/[^0-9]/i', '', $v);
}, $prices)) / count($prices);
$total = 0;
foreach ($prices as $index => $value)
$total += preg_replace('/[^0-9]/i', '', $value);
echo "€" . number_format($total);
function getCleanArray($prices)
{
$pricesCleaned = array();
foreach ($prices as $value)
{
$pricesCleaned.push(preg_replace('/[^0-9]/i', '', $value));
}
return $pricesCleaned;
}
調用此方法后,您將獲得帶有數字的數組,可以進一步對其進行操作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.