在JSON数组中查找对象

时间:2016-01-26 06:20:43

标签: php json linkedin

我不能为我的生活找到正确的语法来返回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引入此元素的语法。

任何帮助都将不胜感激。

2 个答案:

答案 0 :(得分:2)

如果它是一个静态的json而不是你可以使用json_decode

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

<强>解释

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

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

答案 1 :(得分:1)

尝试在变量中获取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'];