Reputation: 1087
I have an array. Looks like this:
[
{
"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",
Is there a posibility convert all numeric fileds like 2
or 51.20
to ints and floats respectively (I mean not manually) ?
Manually I do it this way:
foreach ($array as &$val) {
foreach ($val as &$value) {
if(is_numeric($value)){
if(ctype_digit($value))
$value= (int)$value;
else
$value = (float)$value;
}
}
}
Upvotes: 0
Views: 39
Reputation: 91762
If the depth of your array can vary and you want it to work for all levels, you can use array_walk_recursive()
:
array_walk_recursive($arr, function(&$val) {
if (is_numeric($val)) {
if (ctype_digit($val)) {
$val= (int) $val;
} else {
$val = (float) $val;
}
}
});
An example.
Upvotes: 1