Search code examples
phprestapijira-agilephp-curl

PHP - How to dynamically add array to Object request


I am doing Jira REST API calls and I am wondering how I can dynamically add more than one component to the components field using REST API in PHP. I have the following code, works when I set it static, but not sure how to do it dynamically.

Example of static component set:

$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"
        )
    )
),
);

My array that I want to replace the static content with:

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

Replacing

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

with

'components' => [
                    $arr
                ]

doesn't work, I get:

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

I see on an api call to get a request it looks like this:

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

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

            )

But I am unsure how to transform an array into this type of object or request in PHP. Calling with PHP-cURL and json_encoding the data it sends.

Thanks in advance!


Solution

  • To fix this I had to do the following:

    When creating the array from the DB:

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

    Then to set the component in the request:

    'components' => $arr
    

    Thanks