我有一个像下面这样的json
{"root":{
"version":"1",
"lastAlarmID":"123",
"proUser":"1",
"password":"asd123##",
"syncDate":"22-12-2014",
"hello.world":"something"
}
}
在json_decode()
之后,我可以得到除了最后一个hello.world
之外的所有值,因为它包含一个点。
$obj->root->hello.world
不工作。我有Javascript的解决方案但我想要php的
$obj->root->{'hello.world'}
将工作。
ps: $obj->root->{hello.world}
可能无法工作。
b.t。w:为什么不用Array?json_decode($json, true)
将返回Array。那么$a['root']['hello.world']
将始终工作
这里有两个选项:
第一个选项:将对象转换为数组,并以这种方式访问属性,或者将名称转换为安全的名称:
<?php
$array = (array) $obj;
// access the value here
$value = $array['hello.world'];
// assign a safe refernce
$array[hello_world] = &$array['hello.world'];
第二个选项:使用引号和括号:
<?php
$value = $obj->root->{'hello.world'};
正常运行
echo $test->root->{'hello.world'};
检查示例
<?php
$Data='{"root":{
"version":"1",
"lastAlarmID":"123",
"proUser":"1",
"password":"asd123##",
"syncDate":"22-12-2014",
"hello.world":"something"}
}';
$test=json_decode($Data);
print_r($test);
echo $test->root->{'hello.world'};
?>
输出
something
您可以使用可变变量(http://php.net/manual/en/language.variables.variable.php):
)$a = 'hello.world';
$obj->root->$a;