5

I'm using PHP v5.6.

As i read that php json_encode function is automatically converting int to string. But not in my case. Json_encode is still return it to int not string.

Like example:

json_encode(['code' => 200, 'results' => [id=> 1]]);

my expected results is all become a string. but what i get is

{"code":200,"results":{"id": 1}}

Expected output:

{"code":"200","results":{"id": "1"}}

How can i change all the result become string without using "" for every value?.

NB: results array is based on query.

online Thomas
  • 8,864
  • 6
  • 44
  • 85
ssuhat
  • 7,387
  • 18
  • 61
  • 116

3 Answers3

6

In the link posted by Thomas in comments, one user suggests that you do this:

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

This might not be the most efficient in terms of performace though, since every entry on the array will pass through the strval function.

Community
  • 1
  • 1
Marcos Dimitrio
  • 6,651
  • 5
  • 38
  • 62
  • yes. at last i got a way to use array_map and array walk properly. so it can change all the int to string automatically. Thanks for the heads up! – ssuhat Nov 16 '15 at 02:02
  • This is only a suitable technique if the input array is guaranteed to be one-dimensional. Otherwise, there will be problems https://3v4l.org/GcIma. – mickmackusa Apr 09 '21 at 15:12
  • @Marcos Dimitrio thanks for your answer its works like charm. – Shamsi786 Sep 08 '21 at 12:43
0
json_encode(['code' => 200, 'results' => [id=> strval(1)]]);

With strval() php will return

The string value of var.

online Thomas
  • 8,864
  • 6
  • 44
  • 85
  • yes. i use strval. but its from query result. if i use strval it will be a lot of value to use strval() – ssuhat Nov 14 '15 at 07:24
  • @sstarlight are you affraid it might influence performance, what is exactly the problem with ` it will be a lot of value to use strval() `? – online Thomas Nov 14 '15 at 07:28
  • I mean. if inside results. i have 50 value. and it need to convert to strval. It will be not efficient enough. – ssuhat Nov 14 '15 at 07:32
  • Yes, this would be rather painstaking to manually call `strval()` on 50 columns in a result set. – mickmackusa Apr 09 '21 at 15:14
0

To ensure that all numeric "leaf nodes" of a potentially multi-dimensional array are cast as strings, call array_walk_recursive() and make conditional changes to each value type. By checking if the value "is numeric", you prevent values like null and booleans from being cast as strings.

Code: (Demo)

$array = [
    'code' => 200,
    'results' => [
        'id' => 1
    ],
    'a' => [
        [
            'b' => [
                4,
                null,
                false
            ]
        ]
    ]
];

array_walk_recursive(
    $array,
    function(&$v) {
        if (is_numeric($v)) {
            $v = strval($v);
        }
    }
);
echo json_encode($array);

Output:

{"code":"200","results":{"id":"1"},"a":[{"b":["4",null,false]}]}
mickmackusa
  • 43,625
  • 12
  • 83
  • 136