Return to Snippet

Revision: 31360
at September 3, 2010 07:30 by jvandemerwe


Initial Code
<?php

// json is here a field, but can be your input too. This is for educational purposes
// this sample is the output from an Extjs Ajax call, submitting a complete grid back
// to the server

$json = '{
    "success" : "true",
    "message" : "OK",
    "total"   : "3",
    "records" : [
        {
            "se_pkey": "DE",
            "se_langvalue": "Deutsch",
            "se_picon": "de",
            "se_pvalue": "Lehrinstitut",
            "se_pshow": "1",
            "se_id": "216" 
        },
        {
            "se_pkey": "EN",
            "se_langvalue": "Englisch",
            "se_picon": "en",
            "se_pvalue": "Institute",
            "se_pshow": "1",
            "se_id": "227" 
        },
        {
            "se_pkey": "NL",
            "se_langvalue": "Niederl\u00e4ndisch",
            "se_picon": "nl",
            "se_pvalue": null,
            "se_pshow": null,
            "se_id": null 
        } 
    ]
}';

$exjson = json_decode($json, true);  // decode the json string to an array

foreach ( $exjson['records'] as $row ) {  // loop the records

     echo 'To access fields, this works too:&nbsp;'.  $row['se_id']. '<br/>';

     foreach ( $row as $field => $value ) {  // loop the fields

         // $field = field name
         // $row   = record
         // $value = field value

         echo $field . ': '. $value . '<br>';
     }
     echo '<br/>'; 
}

?>

Initial URL

                                

Initial Description

                                

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

Initial Tags
php, json

Initial Language
PHP