JSON看起来像这样
{
73: {
id: 74,
title: "39",
body: "11100000000000000000#IS#2.5",
created_at: "2018-04-23 21:19:19",
updated_at: "2018-04-23 21:19:19"
}
}
我需要在不知道73是什么的情况下访问73的值。
echo $studentData->;
答案 0 :(得分:1)
您可以使用reset()
获取对象的第一个成员:
$json = '{"73":{"id":74,"title":"39","body":"11100000000000000000#IS#2.5","created_at":"2018-04-23 21:19:19", "updated_at":"2018-04-23 21:19:19"}}';
$data = json_decode($json);
$first = reset($data);
var_dump($first);
输出:
object(stdClass)#1 (5) {
["id"] => int(74)
["title"] => string(2) "39"
["body"] => string(27) "11100000000000000000#IS#2.5"
["created_at"] => string(19) "2018-04-23 21:19:19"
["updated_at"] => string(19) "2018-04-23 21:19:19"
}
答案 1 :(得分:0)
一个选项是使用json_decode($jsonData, true)
将json解码为数组,其中$ jsonData是您的json对象。这将为您提供一个数组,然后您可以获得该数组的第73个索引。
答案 2 :(得分:0)
使用正则表达式的替代解决方案
$str = '{"73":{"id":74,"title":"39","body":"11100000000000000000#IS#2.5","created_at":"2018-04-23 21:19:19", "updated_at":"2018-04-23 21:19:19"}}';
preg_match('/{.*?({.*?}).*?}/s', $str, $matches, PREG_OFFSET_CAPTURE, 0);
$result = json_decode($matches[1][0]);
var_dump($result);
结果:
object(stdClass)[1]
public 'id' => int 74
public 'title' => string '39' (length=2)
public 'body' => string '11100000000000000000#IS#2.5' (length=27)
public 'created_at' => string '2018-04-23 21:19:19' (length=19)
public 'updated_at' => string '2018-04-23 21:19:19' (length=19)