Atural
Atural

Reputation: 5439

Mysql / PHP / json_encode boolean string conversion

I have a mysql query lets 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 an array back with true / false as a string

If I use json_encode the result is like {"id":"false"}

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

Of course I can run a str_replace to the json string - but i think there are alternatives isn't it?

Upvotes: 8

Views: 25256

Answers (3)

Intranets
Intranets

Reputation: 1

I had the same problem :

I used PHP for convert value gettype, 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

Upvotes: 0

Lucas Green
Lucas Green

Reputation: 3959

The problem here is that the data returned from mysql is a string, not a boolean. If you know that it is always going to be either '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 later, when it is json_encoded() it will be represented as a primitive boolean, instead of a string.

Upvotes: -1

deceze
deceze

Reputation: 522024

Well, you are selecting from the database as string. So that's what gets encoded. Use SQL true/false boolean values, which in PHP become 0/1, and cast them to PHP booleans before JSON encoding them:

$data['id'] = (bool)$data['id']; // 0/1 -> PHP false/true

echo json_encode($data); // {'id':true}

Upvotes: 19

Related Questions