8

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?

4
  • how are you going to end up using the boolean? in JavaScript? Commented Apr 18, 2014 at 11:43
  • i use jstree and jstree demands a notation like {"children":false} Commented Apr 18, 2014 at 11:45
  • If you use php you can do like: $result[]['children'] = $data['children']? true: false; What do you think? Commented Apr 18, 2014 at 11:45
  • yes i think i can do that - but i've to iterate through the array - in this case i can use str_replace too which seems not the best solution here - i don't want to iterate through the given array just because of that Commented Apr 18, 2014 at 11:48

3 Answers 3

19

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}
Sign up to request clarification or add additional context in comments.

1 Comment

yeah in this case i've to iterate through the array too - but i guess you r right - this seems the best solution for now
0

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

Comments

-1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.