How to access a JSON in PHP easy (like a JSON recordset with multiple fields)


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



Copy this code and paste it in your HTML
  1. <?php
  2.  
  3. // json is here a field, but can be your input too. This is for educational purposes
  4. // this sample is the output from an Extjs Ajax call, submitting a complete grid back
  5. // to the server
  6.  
  7. $json = '{
  8. "success" : "true",
  9. "message" : "OK",
  10. "total" : "3",
  11. "records" : [
  12. {
  13. "se_pkey": "DE",
  14. "se_langvalue": "Deutsch",
  15. "se_picon": "de",
  16. "se_pvalue": "Lehrinstitut",
  17. "se_pshow": "1",
  18. "se_id": "216"
  19. },
  20. {
  21. "se_pkey": "EN",
  22. "se_langvalue": "Englisch",
  23. "se_picon": "en",
  24. "se_pvalue": "Institute",
  25. "se_pshow": "1",
  26. "se_id": "227"
  27. },
  28. {
  29. "se_pkey": "NL",
  30. "se_langvalue": "Niederl\u00e4ndisch",
  31. "se_picon": "nl",
  32. "se_pvalue": null,
  33. "se_pshow": null,
  34. "se_id": null
  35. }
  36. ]
  37. }';
  38.  
  39. $exjson = json_decode($json, true); // decode the json string to an array
  40.  
  41. foreach ( $exjson['records'] as $row ) { // loop the records
  42.  
  43. echo 'To access fields, this works too:&nbsp;'. $row['se_id']. '<br/>';
  44.  
  45. foreach ( $row as $field => $value ) { // loop the fields
  46.  
  47. // $field = field name
  48. // $row = record
  49. // $value = field value
  50.  
  51. echo $field . ': '. $value . '<br>';
  52. }
  53. echo '<br/>';
  54. }
  55.  
  56. ?>
  57.  

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.