Skip to content Skip to sidebar Skip to footer

Force Json_encode To Create Strings Of Numeric Values In A Flat Array

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 integers instead of string

Solution 1:

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...

Solution 2:

Define them in your array as strings, or if it is coming from somewhere else:

$data = json_encode(array_map('strval', $data));

Solution 3:

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)

Solution 4:

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.

functionJSON_NUMERIC_STRING($array){
    foreach($arrayas$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);

Post a Comment for "Force Json_encode To Create Strings Of Numeric Values In A Flat Array"