Calipso
Calipso

Reputation: 967

foreach in json decode not working

I want to get key and values from a json string like below

JSON :

[{
    "EXTAPP_ID": "9901",
    "CATEGORY_ID": "10",
    "LANGUAGE_CODE": "tr",
    "CATEGORY_LANG_DESC": "Sat\u0131\u015f Departman\u0131"
}, {
    "EXTAPP_ID": "9901",
    "CATEGORY_ID": "10",
    "LANGUAGE_CODE": "de",
    "CATEGORY_LANG_DESC": "Sales Abteilung"
}, {
    "EXTAPP_ID": "9901",
    "CATEGORY_ID": "20",
    "LANGUAGE_CODE": "de",
    "CATEGORY_LANG_DESC": "Procurement Abteilung"
}, {
    "EXTAPP_ID": "9901",
    "CATEGORY_ID": "20",
    "LANGUAGE_CODE": "tr",
    "CATEGORY_LANG_DESC": "Sat\u0131nalma Departman\u0131"
}, {
    "EXTAPP_ID": "9901",
    "CATEGORY_ID": "10",
    "LANGUAGE_CODE": "en",
    "CATEGORY_LANG_DESC": "Sales Department"
}, {
    "EXTAPP_ID": "9901",
    "CATEGORY_ID": "20",
    "LANGUAGE_CODE": "en",
    "CATEGORY_LANG_DESC": "Procurement Department"
}]

PHP :

$string = json_decode($_POST['json'], true);
foreach($string as $key => $value) {
  echo $key . " : " . $value;
}

it returns

0 : Array1 : Array2 : Array3 : Array4 : Array5 : Array

Upvotes: 0

Views: 1065

Answers (2)

FreshPro
FreshPro

Reputation: 873

You're returning an array of objects not values. You need to parse that object like :

foreach($string as $object) {
      foreach($object as $key => $value) {
          echo "Key :" .$key;
          echo "Value :" . $value;
       }
}

Upvotes: 0

jszobody
jszobody

Reputation: 28911

You are getting that output because your JSON has an array of objects (which PHP is parsing as an array of arrays). You need a nested loop:

foreach($string AS $array) {
    foreach($array AS $key => $value) {
        echo $key . " : " . $value;
    }
}

Working example: http://3v4l.org/Ee1iF

Upvotes: 1

Related Questions