2013-10-31 20 views
0

我有一個陣列$prices = array();。該數組包含許多顯示價格的條目。如何添加數組的所有值併除以條目總數?

例如€ 2.500

我的目標是增加所有這些價值觀,並具有平均數。但首先,擁有在2500

的格式€ 2.500這是我所知道的,它是通過使用

preg_replace('/[^0-9]/i', '', $variable); 

有什麼辦法做到這一點呢?

謝謝

+0

這也被稱爲「計算平均值」。 – user2864740

回答

2

您可以使用array_map於正則表達式應用到每個元素。

$avg = array_sum(array_map(function($v){ 
    return preg_replace('/[^0-9]/i', '', $v); 
}, $prices))/count($prices); 
+0

謝謝你,但我無法得到它的工作。我編輯了我的問題,添加了'$ prices = array();'而不是'prices []' – EnexoOnoma

+0

@Shilloftanos:'var_dump($ prices);'show? –

+0

'array(2){[0] => array(9){[0] => string(34)「€1.500」[1] => string(34)「€4.500」'並繼續 – EnexoOnoma

1
$total = 0; 
foreach ($prices as $index => $value) 
    $total += preg_replace('/[^0-9]/i', '', $value); 

echo "€" . number_format($total); 
0
function getCleanArray($prices) 
{ 
    $pricesCleaned = array(); 

    foreach ($prices as $value) 
    { 
     $pricesCleaned.push(preg_replace('/[^0-9]/i', '', $value)); 
    } 

    return $pricesCleaned; 
} 

這個方法調用後,你會得到陣列,它可以進一步處理數字。

相關問題