将数组传递给API

时间:2015-01-05 05:29:10

标签: php

我正在尝试将数组传递给API,当我在POSTMAN (raw form)中运行时,API采用以下格式的数组,

{
"records": [
    {
    "content": "50.150.50.55",
    "type": "A",
    "name": "test.mauqe.com",
    "prio": null,
    "ttl": 3600
    }
    ]
}

当我试图以这种格式在我的代码中传递数组时,

 $data = array(
             "content" => "50.150.50.55",
             "type" => "A",
             "name" => "gulpanra.mauqe.com",
             "prio" => "null",
             "ttl" => "3600"
             );

我不明白,问题是什么。响应表示错误 (Data sending format error) 。请帮忙

5 个答案:

答案 0 :(得分:2)

API需要一组地图。以下是一系列地图。

[
    {
    "content": "50.150.50.55",
    "type": "A",
    "name": "test.mauqe.com",
    "prio": null,
    "ttl": 3600
    },
    {},
    {},
    ...
]

你传递的是不一样的。你传递的是一张地图

{
         "content" => "50.150.50.55",
         "type" => "A",
         "name" => "gulpanra.mauqe.com",
         "prio" => "null",
         "ttl" => "3600"
 }

尝试将$ data修改为:

$data = array();

array_push($data['records'], array(
         "content" => "50.150.50.55",
         "type" => "A",
         "name" => "gulpanra.mauqe.com",
         "prio" => "null",
         "ttl" => "3600"
));

答案 1 :(得分:1)

使用json_encode以json格式转换数组,然后将其传递给api。

您正在使用的Api期待json格式的数据。

$data = json_encode($data);

答案 2 :(得分:1)

<?php
$data = array('records' => array());
$data['records'][] = array( 

                "content" => "50.150.50.55",
                "type" => "A",
                "name" => "gulpanra.mauqe.com",
                "prio" => null,
                "ttl" => 3600

        );

$json_output = json_encode( $data );
echo $json_output;
?>

这将输出以下内容:

{"records":[{"content":"50.150.50.55","type":"A","name":"gulpanra.mauqe.com","prio":null,"ttl":3600}]}

答案 3 :(得分:0)

您需要将数组转换为json格式才能将其传递给api。使用json_encode()。使用以下代码

$array = array( "content" => "50.150.50.55", "type" => "A", "name" => "gulpanra.mauqe.com", "prio" => "null", "ttl" => "3600" );
$data = json_encode($data); // Pass this to API

希望这有助于你

答案 4 :(得分:0)

你必须在外面制作数组

您正在使用此类型的数组进行编码

$data['records'] = array(
       'content' => '50.150.50.55',
       and so on
);

将此数组更改为此

$data = array(
  'content' => '50.150.50.55',
   and so on
);

这将有助于