当前位置: 动力学知识库 > 问答 > 编程问答 >

php - types (integer, Boolean,..) in JSON by using JSON_encode

问题描述:

I have an array similar to :

 [0] => stdClass Object

(

[name] => John

[id] => 1

[pass] => 0

)

The array is returned by a sql query. Now I need to use json_encode and I want the id to be integer and pass Boolean, but they get string types after json_encode. How can I do it with the correct datatypes in json_encode?

网友答案:

You could loop through the array, casting each value with the key of pass to a boolean and each id to an integer like so:

<?php

foreach ($results as $result) {
    $result->id = (int) $result->id;
    $result->pass = (bool) $result->pass;
}
网友答案:

For the type conversions, you can iterate over the list first and cast the relevant properties:

foreach($data as $d)
{
    $d->id = (int)$d->id;
    $d->pass = (bool)$d->pass;
}

For the string conversion issue; the 2nd argument of json_encode() is options (a bitmask). The available options are listed here. The relevant option in your case is JSON_NUMERIC_CHECK, which will prevent your numbers from being converted to strings in the resulting JSON:

$json = json_encode($data, JSON_NUMERIC_CHECK);
网友答案:

id is integer. to make pass boolean set it as boolean (using true, false) or cast it to boolean:

$obj->pass = (bool)$obj->pass;
分享给朋友:
您可能感兴趣的文章:
随机阅读: