【问题标题】:How to create json array php with childs如何使用孩子创建 json 数组 php
【发布时间】:2020-07-14 06:58:50
【问题描述】:

我正在努力编码 json 数据

当发布到 confluenec 时,它需要是

{"id":"282072112","type":"page","title":"new page","space":{"key":"BLA"},"body":{"storage":{"value":"<p>This is the updated text for the new page</p>","representation":"storage"}},"version":{"number":2}}'

所以在我创建的 php 中


$data = array('id'=>$siteid, 'type'=>'page', 'title'=>'title of the page');

$data_json = json_encode($data);


print_r ($data_json);

最终结果应该是这样的

{
  "id": "282072112",
  "type": "page",
  "title": "new page",
  "space": {
    "key": "BLA"
  },
  "body": {
    "storage": {
      "value": "<p>This is the updated text for the new page</p>",
      "representation": "storage"
    }
  },
  "version": {
    "number": 2
  }
}

但我怎样才能添加孩子等?

谢谢

【问题讨论】:

  • 你可以尝试json_decode( $json, true);你的目标字符串,然后print_r()结果看看数组是如何嵌套的。

标签: php


【解决方案1】:

您可以像在 JavaScript 中那样将数据嵌套在数组中:

$data = [
    'id' => $siteid,
    'type' => 'page',
    'title' => 'new page',
    'space' => [
        'key' => 'BLA',
    ],
    'body' => [
        'storage' => [
            'value' => '<p>...</p>',
            'representation' => 'storage'
        ],
    ],
    'version' => [
        'number' => 2,
    ],
];

// as JSON in one line:
echo json_encode($data);

// or pretty printed:
echo json_encode($data, JSON_PRETTY_PRINT);

【讨论】:

    【解决方案2】:
    $data = [
      "id" => $siteid,
      "type" => "page",
      "space" => ["key" => "bla"]
     //...
    ]
    

    您可以嵌套数组。 另见:Shorthand for arrays: is there a literal syntax like {} or []?https://www.php.net/manual/en/language.types.array.php

    【讨论】:

      【解决方案3】:

      试试看

      $data_child = array( 'value'=> 'blablabla' );
      $data = array('id'=>$siteid, 'type'=>'page', 'title'=>'title of the page', 'child' => $data_child );
      
      $data_json = json_encode($data);
      

      【讨论】:

        【解决方案4】:

        您可以通过这种方式创建嵌套数组并在json_encode()之后发送它

        <?php
        $preparing_array = array
            (
            "id" => 282072112,
            "type" => "page",
            "title" => "new page",
            "space" => array
            (
                "key" => "BLA"
            ),
            "body" => array
            (
                "storage" => array
                (
                    "value" => "<p>This is the updated text for the new page</p>",
                    "representation" => "storage"
                )
            ),
            "version" => array
            (
                "number" => 2
            )
        );
        echo json_encode($preparing_array, JSON_PRETTY_PRINT);
        ?>
        

        演示: https://3v4l.org/16960

        【讨论】:

          猜你喜欢
          • 2016-01-17
          • 2011-10-08
          • 1970-01-01
          • 1970-01-01
          • 2020-04-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-04-02
          相关资源
          最近更新 更多