force json_encode to create strings

后端 未结 4 1789
感动是毒
感动是毒 2020-12-21 14:51

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

相关标签:
4条回答
  • 2020-12-21 15:16

    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);
    
    0 讨论(0)
  • 2020-12-21 15:18

    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)
    
    0 讨论(0)
  • 2020-12-21 15:22

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

    0 讨论(0)
  • 2020-12-21 15:26

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

    $data = json_encode(array_map('strval', $data));
    
    0 讨论(0)
提交回复
热议问题