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条)

报告相同问题?

悬赏问题

  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统