使用json_decode从JSON对象获取密钥名称

时间:2018-08-08 05:34:13

标签: php json

我正在跟踪JSON字符串

{
   "daily":{
      "1518220800000":174,
      "1518307200000":175,
      "1518393600000":179,
      "1518480000000":181
   },
   "average":{
      "1518220800000":171,
      "1518307200000":171,
      "1518393600000":171,
      "1518480000000":172
   }
}

并且我想使用PHP访问1518220800000对象中的第一个键名daily

2 个答案:

答案 0 :(得分:1)

这将满足您的要求:

$jsonstr = '{
   "daily":{
      "1518220800000":174,
      "1518307200000":175,
      "1518393600000":179,
      "1518480000000":181
   },
   "average":{
      "1518220800000":171,
      "1518307200000":171,
      "1518393600000":171,
      "1518480000000":172
   }
}';
$json = json_decode($jsonstr, true);
echo array_keys($json['daily'])[0];

输出:

1518220800000

答案 1 :(得分:1)

阅读this,了解如何从嵌套数组中获取数据:

$data = '{
   "daily":{
      "1518220800000":174,
      "1518307200000":175,
      "1518393600000":179,
      "1518480000000":181
   },
   "average":{
      "1518220800000":171,
      "1518307200000":171,
      "1518393600000":171,
      "1518480000000":172
   }
}';

$character = json_decode($data,true);
echo $character[daily][1518220800000];

输出:174