I have to json_encode a PHP array to a JavaScript array. Unfortunately the jQuery library I am using will not properly process that array if it contains ints instead of stri
Because there isn't an opposite flag for JSON_NUMERIC_CHECK
, I've created a function for that purpose.
It accepts one and multi dimensional arrays and there can be added for conditions to validate each element of te array.
function JSON_NUMERIC_STRING($array){
foreach($array as $key => &$value){
if(is_array($value)){
$value = iterateMA($value);
}elseif(is_numeric($value)){
$value = strval($value);
}
// add more conditions if needed...
}
return $array;
}
$array = JSON_NUMERIC_STRING($array);
json_decode()
can convert large integers to strings, if you specify a flag in the function call:
$array = json_decode($json, true, 512, JSON_BIGINT_AS_STRING)
It would be nice if there was the opposite of JSON_NUMERIC_CHECK
but it doesn't look like there is.
Why can't you ensure the data is of the correct type in your php, before encoding it?
This might mean you have to cast it manually to strings...
Define them in your array as strings, or if it is coming from somewhere else:
$data = json_encode(array_map('strval', $data));