0

I have written a script to query a mysql database and encode the data in json format.

I have added $encoded = json_encode($encodable[0]); which removes the other [ ] brackets but then only displays 1 record. Is there a way to still remove those brackets but display for example every record that I am querying?

Sorry not sure how to describe the problem in a better way!

2
  • 1
    Provide some sample input and output. Commented Oct 8, 2011 at 13:59
  • Might be missing something here but if you remove the [ ] brackets without parsing the data surely the JSON will become invalid? Commented Oct 8, 2011 at 14:01

1 Answer 1

0

Encode the result set of the query as JSON? Or encode data that is being sent to the database??

$encodeable[0] is the first element of the array, so its clear that that is what will be encoded. Depending on the format of your data, encodeable[0] would be [{"key":"value"},{"key":"value"},{"key":"value"}] by default as thats an indexed array with keys of 0,1,2...

If your goal is to just output the json as a JS object {}, instead of an array [] you can use json_encode($array, JSON_FORCE_OBJECT); which will encode indexed arrays as {"0":"value"} or {"0":{"0":"value"}} instead of just ["value"] or [["value"]]. If that's not what you're after, you may just need to loop through each encodeable element of your array and encode that way (use a for loop)

http://php.net/manual/en/function.json-encode.php

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

6 Comments

Ok this is the code I am using could you tell me where I put JSON FORCE OBJECT? $encodable = array(); mysql_connect(localhost, $username, $password); mysql_select_db($database) or die("Unable to select database"); $result = mysql_query($sql); while($obj = mysql_fetch_object($result)) { $encodable[] = $obj; } $encoded = json_encode($encodable); echo $encoded; mysql_close();
Thanks I have added that but now it just echos "ArrayJSON_FORCE_OBJECT"
o_O Sorry about that, somehow I put a dot instead of a comma lol; $encoded = json_encode($encodable, JSON_FORCE_OBJECT) (thats the reason why it says array, it was concatenating it)
Warning: json_encode() expects exactly 1 parameter, 2 given in
Ah... you need PHP 5.3.0 or greater to use the JSON_FORCE_OBJECT option... Try this (stackoverflow.com/questions/2634009/…) if you can't upgrade your PHP version. json_encode((object)$encodable);
|

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.