在json解码不能正常工作

时间:2013-11-25 15:34:57

标签: php json decode

我想从json字符串中获取键和值,如下所示

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;
}

返回

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

2 个答案:

答案 0 :(得分:1)

您正在获取该输出,因为您的JSON具有一个对象数组(PHP正在将其解析为数组数组)。你需要一个嵌套循环:

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

工作示例:http://3v4l.org/Ee1iF

答案 1 :(得分:0)

您将返回一个对象数组而不是值。您需要解析该对象,如:

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