簡體   English   中英

如何將數組的所有值相加並除以條目總數?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM