[英]PHP - str_replace not working in multidimensional array
I have a large array.我有一个大数组。 This is an example part of my array:
这是我的数组的示例部分:
13 => [
'Discount' => '0.00'
'Total amount' => '50,00'
'Total Net' => '40,00'
]
14 => [
'Discount' => '0.00'
'Total amount' => '20,00'
'Total Net' => '16,00'
]
I need to convert the commas in the numbers to dots.我需要将数字中的逗号转换为点。
'50,00'
needs to become '50.00'
for example. '50,00'
需要变成'50.00'
。 What's an easy way to do this?有什么简单的方法可以做到这一点?
Note: I tried $myArray = str_replace(',', ".", $dataArray);
注意:我试过
$myArray = str_replace(',', ".", $dataArray);
but this doesnot work.但这不起作用。
You have to loop over the array
value's你必须遍历
array
值的
foreach ($array as $key => $string) {
$array[$key] = str_replace(',', '.', $string);
}
Since it's a multidimensional array you need to loop nested with both the subarray and the value by reference.由于它是一个多维数组,您需要循环嵌套子数组和引用值。
Or have the subarray as the input in the str_replace.或者将子数组作为 str_replace 中的输入。 (u_mulder)
(u_mulder)
foreach($arr as &$val){
$val = str_replace(",",".", $val);
}
var_dump($arr);
https://3v4l.org/tSgSP https://3v4l.org/tSgSP
You can also add a check to see if there is a comma in the value before you replace.您还可以在替换之前添加检查以查看值中是否有逗号。
Not sure if that will make it faster or slower though.不确定这是否会使它更快或更慢。
...
if(strpos($val, ",") !== false) $val = str_replace(",",".", $val);
...
I hope this will help you我希望这能帮到您
array_walk_recursive(
$myarray,
function (&$value) {
$value = str_replace(',', '.', $value);
}
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.