PHP JSON解码:带有"$"问题的数组 [英] PHP JSON decode: array with '$' problem
问题描述
我将以下JSON文件作为输入
I have the following JSON file as input,
{
"$type": "NanoWebInterpreter.WebInputData, NanoWebInterpreter",
"NBBList": {
"$type": "System.Collections.Generic.List`1[[monoTNP.Common.NBB, monoTNP.Common]], mscorlib",
"$values": [
{
"$type": "monoTNP.Common.NBB, monoTNP.Common",
"ID": "id-0065-00000003",
"MPList": {
"$type": "System.Collections.Generic.List`1[[monoTNP.Common.MP, monoTNP.Common]], mscorlib",
"$values": [
{
"$type": "monoTNP.Common.EllipticalMP, monoTNP.Common",
"Eccentricity": 1.0,
"ID": "id-0065-00000006",
"ParticleIndex": -1,
"DispersionInteractionStrength": 0.0,
"DispersionInteractionRange": 2.5,
"CharacteristicSize": 0.0,
"CenterOfMass": "<0,0,0>",
"OrientationVector": "<>"
},
{
"$type": "monoTNP.Common.CubeMP, monoTNP.Common",
"ID": "id-0065-00000005",
"ParticleIndex": -1,
"DispersionInteractionStrength": 0.0,
"DispersionInteractionRange": 2.5,
"CharacteristicSize": 0.0,
"CenterOfMass": "<0,0,0>",
"OrientationVector": "<>"
},
{
"$type": "monoTNP.Common.CircularMP, monoTNP.Common",
"ID": "id-0065-00000004",
"ParticleIndex": -1,
"DispersionInteractionStrength": 0.0,
"DispersionInteractionRange": 2.5,
"CharacteristicSize": 0.0,
"CenterOfMass": "<0,0,0>",
"OrientationVector": "<>"
}
]
},
等
我的最终目标是递归地跟踪这棵树,用<ul>
标签包装每个键/对象名称,并以某种<form>
结构包装"ParticleIndex"级别的属性,但是我不知道如何索引两个'$ values'数组.
My ultimate goal is to trace this tree recursively, wrapping each key/object name with <ul>
tags, and the properties at the "ParticleIndex" level in some kind of <form>
structure, but I can't figure out how to index into the two '$values' arrays.
这是我一直在学习如何访问每个元素(对象或数组)的代码:
This is the code that I have been manipulating to learn how each element(object or array) is accessed:
foreach ($json->NBBList->'$values'[0] as $key => $value){
var_dump($key);
echo "\n".var_dump($value);
echo "\n\n\n";
}
这显然是行不通的,因为值的索引在字符串的外部,但是当它在字符串的内部时,PHP会将其解释为字符串的一部分.
This obviously doesn't work because the index of values is outside of the string, but when it is on the inside, PHP interprets it as part of the string.
我是否可以索引"$ values"数组的每个元素,并最终进入for循环?
Is there a way for me to index into each element of the '$values' array, and ultimately in a for loop?
我正在考虑使用JSON解码的"true"属性可能是一个更好的解决方案...
I'm thinking using the "true" property of JSON decode might be a better solution...
推荐答案
您可以使用以下表示法访问名称包含特殊字符的对象属性:
You can access object properties with names that contain special characters using this notation:
$json->NBBList->{'$values'}[0]
我认为此行为在任何地方都没有记录,但是您可以在 PHP语法(请参见variable_name
的定义,该定义在object_dim_list
中使用,在object_property
中使用).
I don't think that this behavior is documented anywhere, but you can find it in the PHP grammar (see definition of variable_name
, which is used in object_dim_list
, which is used in object_property
).
这篇关于PHP JSON解码:带有"$"问题的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!