dongwu9647 2017-05-20 00:44
浏览 21
已采纳

在PHP中创建自定义JSON布局[重复]

This question already has an answer here:

I'm trying to create JSON in a PHP variable that represents the following JSON structure:

{
  "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}
  ]
}

I'm currently not certain if the best way to do this would be to manually format the JSON layout myself, or if the above structure can be achieved using arrays and json_encode(). It would be good it someone could first confirm the best approach here.

The code I currently have is:

$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';

However when I view the output in JSON format there are some issues:

{
    "nodes": ["\"id\": \"example@email.com\", \"group\": 1", "\"id\": \"Device ID 0eb6823c8e826b6ba6a4fba7459bc77c\", \"group\": 2"],
    "links": ["\"source\": \"example@email.com\", \"target\": \"Exact ID 0eb6823c8e826b6ba6a4fba7459bc77c\", \"value\": 1"]
}

As you can see the json_encode is causing additional quotation marks with escape \ characters to be added, and each entry isn't stored as an object. Any guidance you can provide would be sincerely appreciated.

</div>
  • 写回答

2条回答 默认 最新

  • dongluo1853 2017-05-20 01:06
    关注

    It is better using json_encode, note that you should use arrays all the way:

    $entityarray['nodes'][] = array( 'id'    => 'example@email.com'
                                   , 'group' => 1
                                   );
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?