我应该如何处理可能具有对象或数组值的键?
我目前有一些代码可以从网站获取一些 JSON。这基本上就是我目前所做的
$valueObject = array();
if (isset($decoded_json->NewDataSet)) {
foreach ($decoded_json->NewDataSet->Deeper as $state) {
$i = count($valueObject);
$valueObject[$i] = new ValueObject();
$valueObject[$i]->a = $state->a;
}
现在当只有一个“更深”时就会出现问题。服务器将其作为 JSON 对象返回。 $state 然后成为 Deeper 对象中的每个键。例如,$state->a 直到位置 7 左右才会存在。当 Deeper 的计数为 1 时,有什么方法可以将 Deeper 从 JSON 对象转换为数组吗?
希望这有助于说明我的问题:
"NewDataSet": {
"Deeper": [
{
"a": "112",
"b": "1841"
},
{
"a": "111",
"b": "1141"
}
]
}
}
与
"NewDataSet": {
"Deeper":
{
"a": "51",
"b": "12"
}
}
上面的转换
"NewDataSet": {
"Deeper": [
{
"a": "51",
"b": "12"
}
]
}
相比会很棒。我不知道该怎么做
I currently have some code which grabs some JSON from a site. This is basically what I currently do
$valueObject = array();
if (isset($decoded_json->NewDataSet)) {
foreach ($decoded_json->NewDataSet->Deeper as $state) {
$i = count($valueObject);
$valueObject[$i] = new ValueObject();
$valueObject[$i]->a = $state->a;
}
Now the problem occurs when there is only one 'Deeper'. The server returns it as a JSON object. $state then becomes each key in the Deeper object. $state->a won't exist until around position 7 for example. Is there any way I could convert Deeper from a JSON object to array when the count of deeper is one?
Hopefully this helps illustrate my problem:
"NewDataSet": {
"Deeper": [
{
"a": "112",
"b": "1841"
},
{
"a": "111",
"b": "1141"
}
]
}
}
versus
"NewDataSet": {
"Deeper":
{
"a": "51",
"b": "12"
}
}
converting above to
"NewDataSet": {
"Deeper": [
{
"a": "51",
"b": "12"
}
]
}
would be great. I don't know how to do this
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
之前
在
foreach ($decoded_json->NewDataSet->Deeper as $state)
,您可能需要:
更新
如果您只想将
$decoded_json->NewDataSet->Deeper
放入数组中,则:Before
foreach ($decoded_json->NewDataSet->Deeper as $state)
you probably want to:
Update
If you just want to make
$decoded_json->NewDataSet->Deeper
into an array, then: