在 JSON 数组中查找对象


Find Object in JSON Array

我一生都找不到正确的语法来返回 JSON 数组中的元素

该数组是

{
"_total": 1,
"values": [{
"isCommentable": true,
"isLikable": true,
"isLiked": false,
"numLikes": 0,
"timestamp": 1453718959851,
"updateComments": {"_total": 0},
"updateContent": {
  "company": {
    "id": 2691316,
    "name": "Rising 5th Web Design"
  },
  "companyStatusUpdate": {"share": {
    "comment": "This is a test update for testing the jQuery REST API",
    "id": "s6097339248095035392",
    "source": {
      "serviceProvider": {"name": "LINKEDIN"},
      "serviceProviderShareId": "s6097339248095035392"
    },
    "timestamp": 1453718959851,
    "visibility": {"code": "anyone"}
  }}
},
"updateKey": "UPDATE-c2691316-6097339248082460672",
"updateType": "CMPY"
}]
}

我试图达到的元素是

"comment": "这是用于测试 jQuery REST API 的测试更新"

但是没有充分的理由,我无法弄清楚如何将PHP带到这个元素的语法。

任何帮助将不胜感激。

如果它是一个静态 json,那么您可以使用 json_decode

获得:
$content = json_decode($string, true); 
echo $content['values'][0]['updateContent']['companyStatusUpdate']['share']['comment'];

解释:

首先解码您的json并获得正确的索引。

请注意,在此示例中,我使用函数json_decode()第二个参数作为true如果您忽略此参数,您将以OBJECT形式获得解码结果。

尝试将 json 放入变量中,并使用 json_decode() 在 php 中解码 json。

//json variable.
$json ='{
"_total": 1,
"values": [{
"isCommentable": true,
"isLikable": true,
"isLiked": false,
"numLikes": 0,
"timestamp": 1453718959851,
"updateComments": {"_total": 0},
"updateContent": {
  "company": {
    "id": 2691316,
    "name": "Rising 5th Web Design"
  },
  "companyStatusUpdate": {"share": {
    "comment": "This is a test update for testing the jQuery REST API",
    "id": "s6097339248095035392",
    "source": {
      "serviceProvider": {"name": "LINKEDIN"},
      "serviceProviderShareId": "s6097339248095035392"
    },
    "timestamp": 1453718959851,
    "visibility": {"code": "anyone"}
  }}
},
"updateKey": "UPDATE-c2691316-6097339248082460672",
"updateType": "CMPY"
}]
}';
// decode json
    $c = json_decode($json, true);
// get your element
    echo $c['values'][0]['updateContent']['companyStatusUpdate']['share']['comment'];