【问题标题】:Json decode in php basicsphp基础知识中的Json解码
【发布时间】:2013-04-13 20:44:02
【问题描述】:

我正在尝试在 php 中学习 json。这是我的 ElasticSearch 查询的 json 结果。

{
  "took" : 1,
  "timed_out" : false,
  "_shards" : {
    "total" : 5,
    "successful" : 5,
    "failed" : 0
  },
  "hits" : {
    "total" : 1,
    "max_score" : null,
    "hits" : [ {
      "_index" : "xenforo",
      "_type" : "post",
      "_id" : "1816069",
      "_score" : null,
      "sort" : [ 1365037907 ]
    } ]
  }
}

我假设我的 php 代码看起来像这样:

$myData = json_decode($result);

foreach($myData->hits as $var) {
   $post_id[] = $var->_id;
}

几个小时以来一直在寻找答案,我非常感谢任何帮助。谢谢。

编辑:这是答案:

foreach($myData->hits->hits as $var) {
   $post_id[] = $var->_id;
}

【问题讨论】:

  • 你有什么问题?
  • 请参阅array.include-once.org,了解如何在 PHP 中遍历数据结构。仅限->hits->hits is meant to be iterated over
  • 是的,请解释一下这个问题,你想用 JSON 对象完成什么?
  • 我想用 json 输出中的 _id 填充 $post_id 数组。所以在这种情况下 $post_id[0] 应该等于 1816069。
  • 您当前的 JSON 对象仅显示一个 _id 参数,但您所要求的似乎涉及获取多个 _id 所以您可以修改您的 JSON 以便它显示具有多个 _id 的结构的外观?

标签: php json decode


【解决方案1】:

如果你看看你的 JSON 结构,你就是一个 ->hits 短...

{
    "hits" : {
        "hits" : [ {
            "_id" : "1816069",

$myData = json_decode($result);

foreach($myData->hits->hits as $hit) {
    $post_id[] = $hit->_id;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-11
    • 2021-04-07
    • 1970-01-01
    相关资源
    最近更新 更多