PHP - 如何动态添加数组到Object请求

时间:2017-02-05 18:16:05

标签: php rest api jira-agile php-curl

我正在进行Jira REST API调用,我想知道如何使用PHP中的REST API动态地向组件字段添加多个组件。我有以下代码,当我将其设置为静态时,但无法确定如何动态执行它。

静态组件集的示例:

$data = array(

'fields' => array(

    'project' => array(

        'key' => $rowAnswers["Key"]

    ),
    'summary' =>  $rowAnswers["Summary"],

    'description' => $rowAnswers["Description"],

    'issuetype' => array(
        'name' => $rowAnswers["IssueType"]
    ),

    'components' => array(
        array(
            "name" => "component1"
        ),
        array(
            "name" => "component2"
        )
    )
),
);

我想用以下内容替换静态内容的数组:

$components = explode(",", $rowAnswers["Components"]);
        $arr = array();
        foreach($components as $value){
            $array = array("name"=>$value);
            array_push($arr,$array);
        }

更换

'components' => array(
    array(
        "name" => "component1"
    ),
    array(
        "name" => "component2"
    )
)

'components' => [
                    $arr
                ]

不起作用,我明白了:

"{"error":false,"error_msg":"","data":"{\"errorMessages\":[],\"errors\":{\"components\":\"expected Object\"}}"}"

我在api电话上看到获得请求看起来像这样:

[components] => Array
            (
                [0] => stdClass Object
                    (
                        [name] => component1
                    )

                [1] => stdClass Object
                    (
                        [name] => component2
                    )

            )

但我不确定如何在PHP中将数组转换为此类对象或请求。使用PHP-cURL调用并对其发送的数据进行json_encoding。

提前致谢!

2 个答案:

答案 0 :(得分:0)

您需要通过将第二个参数设置为true

来将json解码为关联数组

查看json_decode

  

ASSOC

When TRUE, returned objects will be converted into associative arrays.

答案 1 :(得分:0)

要解决此问题,我必须执行以下操作:

从DB创建数组时:

$components = explode(",", $rowAnswers["Components"]);
        $arr = array();
        foreach($components as $value){
            $array = json_decode(json_encode(array("name"=>$value)), FALSE);
            array_push($arr,$array);
        }

然后在请求中设置组件:

'components' => $arr

由于