【问题标题】:Add array to array with PHP in JSON在 JSON 中使用 PHP 将数组添加到数组
【发布时间】:2022-01-01 17:35:27
【问题描述】:

我正在使用下面的 PHP 代码来生成 JSON 调用。

$Services = array();

$ServiceList[] = array(
  'Name' => 'ideal',
  'Action' => 'Pay'
);
$postArray["Services"]["ServiceList"] = $ServiceList;

$Parameters[] = array(
    'Name' => 'issuer',
    'Value' => 'ASNBNL21'
);
$postArray["Services"]["ServiceList"]["Parameters"] = $Parameters;

$postjson = json_encode($postArray, JSON_PRETTY_PRINT);

但是当我生成数组“Servicelist”时,它给了我错误的 JSON 代码。它显示 "0": { 而不是数组大括号。

"Services": {
        "ServiceList": {
            "0": {
                "Action": "Pay",
                "Name": "ideal"
            },
            "Parameters": [
                {
                    "Name": "issuer",
                    "Value": "ASNBNL21"
                }
            ]
        }
    }

正确的 JSON 代码应如下所示:

"Services": {
    "ServiceList": [
      {
        "Name": "ideal",
        "Action": "Pay",
        "Parameters": [
          {
            "Name": "issuer",
            "Value": "ABNANL2A"
          }
        ]
      }
    ]
  }

【问题讨论】:

  • 尝试将$ServiceList[] 更改为$ServiceList
  • 为什么要创建任何一次性变量? 3v4l.org/QBdUl@Matt

标签: php arrays json


【解决方案1】:

不要从顶层开始,而是从最内层开始:

$parameters = [ 'Name' => 'issuer', 'Value' => 'ASNBNL21' ];
$serviceList = [ 'Name' => 'ideal', 'Action' => 'Pay', 'Parameters' => [ $parameters ] ];
$services = [ 'ServiceList' => [ $serviceList ] ];
$postArray = [ 'Services' => $services ];

$postjson = json_encode($postArray, JSON_PRETTY_PRINT);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-17
    • 1970-01-01
    • 1970-01-01
    • 2012-06-18
    相关资源
    最近更新 更多