2013-03-12 67 views
5

我有混合值的數組:PHP:如果號碼(帶逗號),將其轉換爲正確的數字格式(與點)

$row = array('Unspecified risk','Yes','8','3','2','13','none','-1,49','-2,51','-1,46','-1,54'); -1,94 -1,55 

正如你可以看到它包含文本和消極和積極逗號 - 值。

我需要將數值轉換爲正確的數字格式,並保持文本值不變。

現在我遍歷值:

foreach ($row as $value) { 
    // If $value is numeric, convert it to the 
    // right number format for use with MySQL (decimal(10,2)) 
    // If not, leave it be. 
} 

兩個相關的問題,我已經調查,但無法找到一個合適的解決方案。

誰能提供一個實際的例子?

回答

6

您不需要使用正則表達式。

使用str_replace(),因爲你需要更換',''.',然後用intval()floatval()函數來得到的數值。您還可以使用strstr()來尋找'.',並決定是否使用intval()floatval()

例子:

$row = array('Unspecified risk', 'Yes', '8', '3', '2', '13', 'none', '-1,49', '-2,51', '-1,46', '-1,54'); 

    function toNumber($target){ 
     $switched = str_replace(',', '.', $target); 
     if(is_numeric($target)){ 
      return intval($target); 
     }elseif(is_numeric($switched)){ 
      return floatval($switched); 
     } else { 
      return $target; 
     } 
    } 

    $row = array_map('toNumber', $row); 

    var_dump($row); 

我們使用str_replace()函數來代替點爲逗號,這樣一來它是一種國際符號浮動,即使它是字符串,這種方式稍後我們可以檢查它是否與數字is_numeric() < - 此功能是真棒,因爲它從字符串中檢測,如果它是一個數字或不是,不管是整數或浮點數等。

我們使用is_n數字來檢查該值是整數浮點型還是文本型,並使用intval()floatval()返回相應的值(沒有應用替換的值將不會作爲有效數字返回,僅在切換和之後纔會返回。它將作爲數字返回true)。我們使用$row = array_map('toNumber', $row);將更改應用到數組。

利潤的xD

+0

謝謝回答。但是,我如何區分文本值和數字值? – maartenmachiels 2013-03-12 14:05:24

+0

與is_numeric(),檢查我的編輯:D – aleation 2013-03-12 14:17:37

+0

非常優雅的解決方案!感謝您的努力:它像一個魅力。 – maartenmachiels 2013-03-12 14:39:48

1
$row = array('Unspecified risk','Yes','8','3','2','13','none','-1,49','-2,51','-1,46','-1,54'); 
    foreach($row as $key => $var) { 
     if(strstr($var, ",") && !is_numeric($var)) { 
      $var1 = str_replace(",","", $var); 
      if(is_numeric($var1)) { 
       $decimal = strstr($var, ',', TRUE); 
       $digits = str_replace($decimal, "", $var1); 
       $finalValue = $digits * pow(10,$decimal); 
       $row[$key] = $finalValue; 
      } 
     } 
    } 
    echo "<pre>"; print_r($row); 

注:這將PHP 5.3或PHP 5.3+

+1

checkout floatval()在php文檔中,如果在str_replace()之後使用floatval($ var1),它將直接獲取值。您不需要執行以下4個操作 – aleation 2013-03-12 14:21:18

+1

感謝您的回答! – maartenmachiels 2013-03-12 14:39:08

0

使用is_numeric測試工作,並number_format格式化

foreach ($row as &$value) { 
    $number = str_replace(',','.'); 
    if(is_numeric($number)) 
     $value = number_format($number, 2, '.', ''); 
} 
unset($value); 
相關問題