如何在PHP中迭代JSON数组?

时间:2017-06-15 12:47:46

标签: javascript php arrays json

我尝试了很多解决方案但没有工作。我想在php中迭代json数组。以下是我的json字符串:

{
    "0":
    {
        "problem_id":"13",
        "onset_date":"2011-02-07",
        "status":"Active",
        "operator":"",
        "problem_name":"Allergic Conjunctivitis (372.05)"
    },
    "1":
    {
        "problem_id":"132512",
        "onset_date":"2017-06-12",
        "status":"Active",
        "operator":"",
        "problem_name":"diabetes macular edema - 10"
    },
    "pbids":
    {
        "0":"13",
        "1":"132512"
    }
}

以下是将json字符串发送到服务器的代码:

var finalArrayString = JSON.stringify(convertFormDataToJSONArray());
try{
    alert(JSON.parse(finalArrayString));
    alert(true);
}catch(e){
    alert(false);
}
alert(finalArrayString);
$.ajax({
    url: "index.php",
    type: 'POST',
    data: {problems: finalArrayString},
    beforeSend: function() {},
    success: function(returnedData) {
        alert(returnedData);
    },
    error: function(jqXhr, textStatus, errorThrown){
        alert(errorThrown);
    }
});

以下是我的PHP代码:

if ($_POST['problems'] && $_POST['problems'] != "") {
    $problems = $_POST['problems'];
    foreach ($problems as $key) {
        echo $key;
    }
}

但它什么都没打印。我还使用JSON.parse()检查json字符串是否有效,但它返回true。

2 个答案:

答案 0 :(得分:4)

您需要首先解码JSON。

if ($_POST['problems'] && $_POST['problems'] != "") {
    $problems = json_decode($_POST['problems']);
    foreach ($problems as $key) {
       var_dump($key); // This should print an object out that is key/val'd
    }
}

可以在PHP.net

上找到文档

答案 1 :(得分:-1)

$json  = '[{"var1":"9","var2":"16","var3":"16"},{"var1":"8","var2":"15","var3":"15"}]';

$ array = json_decode($ json,true);    的print_r($阵列);