【问题标题】:How to get specific set of array inside an object如何获取对象内的特定数组集
【发布时间】:2017-06-14 00:17:45
【问题描述】:

所以我这里有一个来自我的 PHP cURL 的 JSON 响应,所以我试图在 location 下获取特定的数组组,这取决于我正在检查的 identifier 值在哪里。

{
"status": "SUCCESS",
"response": {
    "offset": 0,
    "max": 50,
    "count": 2,
    "locations":[
         {
           "identifier":"54320",
           "id": 503892,
           "name":"The Foo"
         },
         {
           "identifier":"54321",
           "id": 503893,
           "name":"The Bar"
         }
    ]
}

这是我到目前为止所做的,也是我正在尝试做的。所以我已经解析了上面的json并将其放在foreach上。请注意,标识符并不总是int,也可以是string

$parsed_json = json_decode($phpCurlResponse, true);
$parsed_json = $parsed_json["response"]["locations"];
    foreach($parsed_json as $key => $pj){
        if($pj['identifier'] == "54320"){
            echo $pj['name'].' & '.$pj['id'];//this should display The Foo & 503892
        }
    }

我试过这个,它只能看到locations 下的第一组array 但是当我将identifier 值从54321 更改为112233 时,响应将是Identifier do not exist. 你能帮助我如何实现这一目标。

【问题讨论】:

  • 您确定标识符为112233的位置是否存在?根据目前提供的信息,一切都按预期工作!?
  • 我仅次于@Jeff,你确定你得到了一个属性为112233的子数组吗?
  • @jeff 嗨,伙计!我再次检查了它,它现在正在工作..我删除了 else 因为它没有必要我认为? ..
  • 在收到的json中,有语法错误,导致json_decode失败:The Bar周围没有"
  • 好的,完成编辑...抱歉造成混乱,因为我只是输入上面的回复来模仿我的回复:D

标签: php arrays json curl


【解决方案1】:

您的 JSON 无效。

  1. locations 数组中的最后一个对象后不应有逗号。
  2. locations 结束数组括号 (]) 之后应该有一个 }

有效的 JSON 也是如此。

{
  "status": "SUCCESS",
  "response": {
    "offset": 0,
    "max": 50,
    "count": 2,
    "locations": [
      {
        "identifier":"54320",
        "id": 503892,
        "name":"The Foo"
      },
      {
        "identifier":"54321",
        "id": 503893,
        "name":"The Bar"
      }
    ]
  }
}

【讨论】:

    【解决方案2】:

    很抱歉过早发布,但我想让您知道上面的代码没有任何问题,只是在我输入的 json 响应中有一些拼写错误,无论如何感谢您的帮助。 :) 所以这是在对象中获取一组特定数组的一种可能方法,具体取决于您要查找的键值在哪里。

    【讨论】:

      猜你喜欢
      • 2021-07-15
      • 2019-11-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-04
      • 2019-08-12
      • 1970-01-01
      相关资源
      最近更新 更多