PHP Array To JSON String


/ Published in: JavaScript
Save to your folder(s)

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]_


Copy this code and paste it in your HTML
  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

You need to login to post a comment.