1

Looking for some help.. Don't know the best approach to this issue... I'm pushing a new reference onto an array but the "true" value is being inserted with quotes, which fails my json format.

 while( $row = mysqli_fetch_assoc($res) ) { 
    if($row['id']=="2"){
    $row['children']= 'true';
    }
    $data[] = $row;
}
echo json_encode( $data);

Outputs

[{"id":"2","name":"john","text":"john","parent_id":"0","children":"true"}]

When i need...

{"id":"2","name":"john","text":"john","parent_id":"0","children":true}]

How would i go about removing the qoutes or inserting it correctly first.??

7
  • for what you what that true as boolean? Commented Sep 18, 2016 at 20:54
  • 1
    JSON data is passed as a STRING so "children":"true" is correct! It will be usable when you get to your javascript and convert it to a javascript object Commented Sep 18, 2016 at 20:55
  • 'true' is a string, true is a boolean. You want a boolean. Commented Sep 18, 2016 at 20:56
  • 1
    Example. Don't do str_replace, please. Commented Sep 18, 2016 at 20:59
  • 1
    @Howzieky You shouldn't use str_replace because it is an unreliable hack. If you put a string in the array, json_encode puts a string in the JSON, if you put a boolean in the array, it puts a boolean in the JSON. Instead of screwing around with the JSON string, just provide json_encode with values that are the correct type to begin with. Commented Sep 18, 2016 at 21:17

1 Answer 1

1

If you want the 'children' to be boolean then set it to boolean.

while( $row = mysqli_fetch_assoc($res) ) { if($row['id']=="2"){ $row['children'] = true; } $data[] = $row; } echo json_encode( $data);

Sign up to request clarification or add additional context in comments.

1 Comment

Oh yeh! Duh!! Feel so stupid now... Thanks Jakub and others for their quick response.. Much appreciated!

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.