【发布时间】:2011-06-11 02:40:09
【问题描述】:
我有以下 JSON 文件作为输入,
{
"$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' 数组。
这是我一直在操作以了解如何访问每个元素(对象或数组)的代码:
foreach ($json->NBBList->'$values'[0] as $key => $value){
var_dump($key);
echo "\n".var_dump($value);
echo "\n\n\n";
}
这显然不起作用,因为值的索引在字符串之外,但是当它在内部时,PHP 将其解释为字符串的一部分。
有没有办法让我索引到“$values”数组的每个元素,并最终在一个 for 循环中?
我正在考虑使用 JSON 解码的“真实”属性可能是一个更好的解决方案...
【问题讨论】:
-
我为你格式化了你的帖子。
-
json不管格式化还是无效。