2017-05-20 107 views
0

我试图在代表以下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造成额外的引号要添加转义\字符,并且每个条目不作为对象存储。您可以提供的任何指导将真诚地感谢。

+0

'PHP的json_encode'会做,更好的利用它来避免错误,如果你有一个前端,你可以使用'JSON.parse(object)'或者如果你有Jquery,你也可以使用'$ .parseJSON(object)' –

+1

[使用PHP创建JSON对象](http://stackoverflow.com/q/20382369/6521116) –

回答

1

最好是使用json_encode,请注意,您应该使用数组一路:

$entityarray['nodes'][] = array('id' => '[email protected]' 
           , 'group' => 1 
           ); 
+0

谢谢萨尔。这正是我所错过的。在你回答之前,我设法弄清楚了那些时刻。最终,我用: $ testarray ['nodes'] [] = array(“id”=>“[email protected]”,“group”=> 1); 而那个伎俩:)谢谢队友! – aktive

0

试试这个

$result = array(); 


$nodes_array = array(); 

$temp = array(); 
$temp["id"] = "[email protected]"; 
$temp["group"] = 1; 

$nodes_array[] = $temp; 

$temp = array(); 
$temp["id"] = "Device ID 0eb6823c8e826b6ba6a4fba7459bc77c"; 
$temp["group"] = 2; 

$nodes_array[] = $temp; 

$temp = array(); 
$temp["id"] = "Device ID 9057673495b451897d14f4b55836d35e"; 
$temp["group"] = 2; 

$nodes_array[] = $temp; 



$links_array = array(); 
$temp = array(); 
$temp["source"] = "[email protected]"; 
$temp["target"] = "Exact ID 0eb6823c8e826b6ba6a4fba7459bc77c"; 
$temp["value"]  =1; 

$links_array[] = $temp; 

$temp = array(); 
$temp["source"] = "[email protected]"; 
$temp["target"] = "Exact ID 9057673495b451897d14f4b55836d35e"; 
$temp["value"]  =1; 


$links_array[] = $temp; 


$result["nodes"] = $nodes_array; 
$result["links"] = $links_array; 





echo json_encode($result);