Mysql / PHP / json_encode boolean logical string conversion

Hey guys, I need help. My mysql query allows me to say:

SELECT cca_id AS id, cca_title AS text,IF((SELECT count(*) from crm_categories WHERE cca_id_prev = id),'TRUE','FALSE') AS children FROM crm_categories WHERE...

now i get the array back with true / false as a string

If I use json_encode, the result will be like {"id":"false"}

but I need true / false without quotes - the problem is that I use true false in the mysql query as a boolean that returns 0/1, but I don't want that ...

Of course, I can run str_replace on a json string - but I think there are alternatives, right?

+7
json php mysql
source share
3 answers

Well, you select from the database as a string. So what is encoded. Use SQL true / false booleans, which in PHP become 0/1 and send them to PHP buffers before JSON encoding:

 $data['id'] = (bool)$data['id']; // 0/1 -> PHP false/true echo json_encode($data); // {'id':true} 
+8
source share

I have the same problem:

I used PHP to convert the gettype value, an example with POST :

 foreach ($_POST as $k => $v) { settype($_POST[$k], gettype($v)); }} echo json_encode($_POST); 

http://php.net/manual/en/function.settype.php

0
source share

The problem is that the data returned from mysql is a string, not a logical one. If you know that it will always be “true” or “false”, you can compare it with a string literal to get the correct type:

 $row = $stmt->fetch(PDO::FETCH_ASSOC); $boolval = ($row['boolval'] === 'true'); 

And then when it will be json_encoded() , it will be presented as a primitive boolean, not a string.

-one
source share

All Articles