我有一个混合值数组:
$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.
}
我调查过两个相关问题,但找不到合适的解决方案。
- Converting a number with comma as decimal point to float
- I need php regular expression for numeric value including "-" and ","
谁能举个例子?
最佳答案
您不需要使用正则表达式。
使用 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() 来替换逗号的点,这样它就是一个国际符号 float ,即使它是字符串,这样稍后我们可以用 is_numeric()
来检查它是否是数字> <-- 这个函数很棒,因为它可以检测字符串是否为数字,无论是整数还是 float 等。
我们使用 is_numeric 来检查值是整数 float 还是文本,并使用 intval()
或 floatval()
返回相应的值(没有替换的值applied 不会作为有效数字返回,只有在切换 , 和 之后。它会作为数字返回 true)。
我们使用 $row = array_map('toNumber', $row);
将更改应用于数组。
利润 xD
关于PHP:如果数字(带逗号),将其转换为正确的数字格式(带点),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15362898/