I have a multidimensional array that has some values that are strings, and some values that are numbers. When I convert the array into a JSON object, I get a result that looks like this:
"A" : "1", "B" : "Text", "C" : "3"
The goal is to have a JSON that looks like this
"A" : 1, "B" : "Text", "C" : 3
Before, I was accomplishing this by editing the JSON after it had been encoded:
$JSON = preg_replace('/"(-?\d+\.?\d*)"/', '$1', json_encode($array));
But that has been problematic for a whole bunch of reasons.
So, instead, before converting the array into a JSON with json_encode(), I’d like to step through all the values and make sure that if a value is a number, then they type for that value is changed from string to int.
I know I can set the type of a variable in PHP with the settype() command:
settype(int, $variable);
I think that I need to combine that with a command like array_walk(), but I don’t know how I would combine it in a way so that it does a test to only act on numbers.
Is it possible in PHP to hunt through a multidimensional array, find values containing only numbers, and convert them into an int type?
You can use the
JSON_NUMERIC_CHECKoption:Or you can loop over the array:
Edit: Just for posterity, the
&turns$valueinto a reference (which points to the actual content of the array item), as opposed to just a variable with a value.