Posted By

inkdeep on 11/10/07


Tagged

php array String json


Versions (?)

Who likes this?

4 people have marked this snippet as a favorite

arcturus
vali29
korzhik
hamiltonmascioli


PHP Array To JSON String


 / Published in: JavaScript
 

SEE http://json.org/ for PHP JSON Libraries.

grunt knuckle drag brute force ugly escapes for quotes make a php array a json string

Produces trailing commas which some Javascript Librarys can't deal with.*

*NOOB NOTE [a comma is added at the end of each array key/value set]

  1. function array_to_json_string($arraydata) {
  2. $output = "";
  3. $output .= "{";
  4. foreach($arraydata as $key=>$val){
  5. if (is_array($val)) {
  6. $output .= "\"".$key."\" : [{";
  7. foreach($val as $subkey=>$subval){
  8. $output .= "\"".$subkey."\" : \"".$subval."\",";
  9. }
  10. $output .= "}],";
  11. } else {
  12. $output .= "\"".$key."\" : \"".$val."\",";
  13. }
  14. }
  15. $output .= "}";
  16. return $output;
  17. }

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: yukimura on January 26, 2009

asd

Posted By: shadyvb on July 26, 2009

there is a native jsonencode() and jsondecode() in php since 5.2.1

You need to login to post a comment.