我试图在代表以下JSON结构的PHP变量创建JSON:创建自定义JSON布局PHP
{
"nodes": [
{"id": "[email protected]", "group": 1},
{"id": "Device ID 0eb6823c8e826b6ba6a4fba7459bc77c", "group": 2},
{"id": "Device ID 9057673495b451897d14f4b55836d35e", "group": 2}
],
"links": [
{"source": "[email protected]", "target": "Exact ID 0eb6823c8e826b6ba6a4fba7459bc77c", "value": 1},
{"source": "[email protected]", "target": "Exact ID 9057673495b451897d14f4b55836d35e", "value": 1}
]
}
我目前不能确定最好的方式做这将是自己手动格式化JSON布局,或者如果使用数组和json_encode()可以实现上述结构。这将是一件好事,有人可以首先确认这里的最佳方法。
我目前拥有的代码是:
$entityarray['nodes'] = array();
$entityarray['links'] = array();
$entityarray['nodes'][] = '"id": "[email protected]", "group": 1';
$entityarray['nodes'][] = '"id": "Device ID 0eb6823c8e826b6ba6a4fba7459bc77c", "group": 2';
$entityarray['links'][] = '"source": "[email protected]", "target": "Exact ID 0eb6823c8e826b6ba6a4fba7459bc77c", "value": 1';
但是当我查看JSON格式的输出有一些问题:
{
"nodes": ["\"id\": \"[email protected]\", \"group\": 1", "\"id\": \"Device ID 0eb6823c8e826b6ba6a4fba7459bc77c\", \"group\": 2"],
"links": ["\"source\": \"[email protected]\", \"target\": \"Exact ID 0eb6823c8e826b6ba6a4fba7459bc77c\", \"value\": 1"]
}
正如你可以看到json_encode造成额外的引号要添加转义\字符,并且每个条目不作为对象存储。您可以提供的任何指导将真诚地感谢。
'PHP的json_encode'会做,更好的利用它来避免错误,如果你有一个前端,你可以使用'JSON.parse(object)'或者如果你有Jquery,你也可以使用'$ .parseJSON(object)' –
[使用PHP创建JSON对象](http://stackoverflow.com/q/20382369/6521116) –