PHP:将数组的所有数值字段分别转换为ins或浮点
我有一个数组。看起来像这样:PHP:将数组的所有数值字段分别转换为ins或浮点,php,arrays,Php,Arrays,我有一个数组。看起来像这样: [ { "id": "2", "number": "2", "debtor_number": null, "name": "Ziegler", "firstname": "Lisa", "credit": "0.00", }, { "id": "3", "number": "3",
[
{
"id": "2",
"number": "2",
"debtor_number": null,
"name": "Ziegler",
"firstname": "Lisa",
"credit": "0.00",
},
{
"id": "3",
"number": "3",
"debtor_number": null,
"name": "Ziegler",
"firstname": "Lisa",
"credit": "51.20",
是否可以将所有数字文件(如2
或51.20
分别转换为整数和浮点值(我的意思是不手动)
我是这样做的:
foreach ($array as &$val) {
foreach ($val as &$value) {
if(is_numeric($value)){
if(ctype_digit($value))
$value= (int)$value;
else
$value = (float)$value;
}
}
}
如果阵列的深度可能不同,并且您希望它适用于所有级别,则可以使用: 安
array_walk_recursive($arr, function(&$val) {
if (is_numeric($val)) {
if (ctype_digit($val)) {
$val= (int) $val;
} else {
$val = (float) $val;
}
}
});