PHP JSON 不能回显值,总是返回一个数组


PHP JSON can't echo values, always returning an array?

我最近开始用 Json 和 ajax 乱搞。

我有这个javascript代码:

var json = {
    "test": [{
        "number":1,
        "char":"hey",
        "bool":true
    }]
};
$.ajax({
    url: "json.php",
    type: "POST",
    contentType: "application/json",
    data: {json: JSON.stringify(json)},
    success: function(res) {
        $("#box").html(res);
    }
});

几分钟前,这段代码工作得非常好,当我这样做时echo $json['test']['number'];它返回1.

但是现在这根本行不通,它说"json"索引是未定义的,因此我尝试使用contentType: "application/x-www-form-urlencoded",它确实有效,但我根本无法获取数组项。

如果我不会在 json_decode() 函数中传递 true 参数,我将收到以下错误:

Cannot use object of type stdClass as array

如果我这样做,我不会得到数据,但响应会说"数组"。

这就是我要回应的:

$json = $_POST['json'];
$json = json_decode($json, true);
echo $json['test'][0];

这就是我对$json var_dump:

array(1) {
  ["test"]=>
  array(1) {
    [0]=>
    array(3) {
      ["number"]=>
      int(1)
      ["char"]=>
      string(3) "hey"
      ["bool"]=>
      bool(true)
    }
  }
}
为什么

它这样做?为什么我不能在不返回数组的情况下从中获取值?

鉴于此:

var json = {
    "test": [{
        "number":1,
        "char":"hey",
        "bool":true
    }]
};

您的 PHP 代码

$json['test']['number'];

只有在test不是数组的情况下才会起作用。上面的,在JavaScript中,看起来像:

json.test.number;

但是test是一个Array,它没有number属性。在 JavaScript 中,这将是查找number的正确方法:

json.test[0].number;

你需要在 PHP 中做同样的事情:

$json['test'][0]['number'];