在PHP中创建自定义JSON布局

在PHP中创建自定义JSON布局,php,arrays,json,Php,Arrays,Json,我试图在PHP变量中创建JSON,该变量表示以下JSON结构: { "nodes": [ {"id": "example@email.com", "group": 1}, {"id": "Device ID 0eb6823c8e826b6ba6a4fba7459bc77c", "group": 2}, {"id": "Device ID 9057673495b451897d14f4b55836d35e", "group": 2} ], "links": [

我试图在PHP变量中创建JSON,该变量表示以下JSON结构:

{
  "nodes": [
    {"id": "example@email.com", "group": 1},
    {"id": "Device ID 0eb6823c8e826b6ba6a4fba7459bc77c", "group": 2},
    {"id": "Device ID 9057673495b451897d14f4b55836d35e", "group": 2}
  ],
  "links": [
    {"source": "example@email.com", "target": "Exact ID 0eb6823c8e826b6ba6a4fba7459bc77c", "value": 1},
    {"source": "example@email.com", "target": "Exact ID 9057673495b451897d14f4b55836d35e", "value": 1}
  ]
}
我目前不确定最好的方法是自己手动格式化JSON布局,还是可以使用数组和JSON_编码实现上述结构。如果有人能在这里首先确认最佳方法,那就太好了

我目前拥有的代码是:

$entityarray['nodes'] = array();
$entityarray['links'] = array();
$entityarray['nodes'][] = '"id": "example@email.com", "group": 1';
$entityarray['nodes'][] = '"id": "Device ID 0eb6823c8e826b6ba6a4fba7459bc77c", "group": 2';
$entityarray['links'][] = '"source": "example@email.com", "target": "Exact ID 0eb6823c8e826b6ba6a4fba7459bc77c", "value": 1';
但是,当我以JSON格式查看输出时,存在一些问题:

{
    "nodes": ["\"id\": \"example@email.com\", \"group\": 1", "\"id\": \"Device ID 0eb6823c8e826b6ba6a4fba7459bc77c\", \"group\": 2"],
    "links": ["\"source\": \"example@email.com\", \"target\": \"Exact ID 0eb6823c8e826b6ba6a4fba7459bc77c\", \"value\": 1"]
}
正如您所看到的,json_编码会导致添加带有转义\字符的附加引号,并且每个条目不会存储为对象。如果您能提供任何指导,我们将不胜感激。

试试这个

 $result = array();


 $nodes_array = array();

 $temp = array();
 $temp["id"] = "example@gmamil.com";
 $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"]    = "example@email.com";
 $temp["target"]    = "Exact ID 0eb6823c8e826b6ba6a4fba7459bc77c";
 $temp["value"]     =1;

 $links_array[] = $temp;

 $temp = array();
 $temp["source"]    = "example@email.com";
 $temp["target"]    = "Exact ID 9057673495b451897d14f4b55836d35e";
 $temp["value"]     =1;


 $links_array[] = $temp;


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





 echo json_encode($result);

最好使用json_encode,注意您应该一直使用数组:

$entityarray['nodes'][] = array( 'id'    => 'example@email.com'
                               , 'group' => 1
                               );

php的json_编码就可以了,最好使用它来避免错误,如果你有前端,你可以使用json.parseobject,如果你有Jquery,你也可以使用$.parsejsonobject,可能是它的副本。这正是我所缺少的。在你回答之前我就想好了。最后,我使用了:$testarray['nodes'][]=arrayid=>email@domain.com组=>1;这就成功了:谢谢你,伙计!