Home > Mobile >  How to convert PHP multidimensional associative array to API http query in the format the API specif
How to convert PHP multidimensional associative array to API http query in the format the API specif

Time:05-14

I have the following array

$folder_data = array(
    "title" => "Testing API Creation",
    "description" => "Testing the Wrike API by creating this folder.",
    "project" => array(
        "status" => "OnHold",
        "startDate" => "2022-05-19",
        "endDate" => "2022-06-19",
        "contractType" => "Billable",
        "budget" => 100
    )
);

When I run it through http_build_query(), it gives me this (urldecode() used for clarity):

title=Testing API Creation&description=Testing the Wrike API by creating this folder.&project[status]=OnHold&project[startDate]=2022-05-19&project[endDate]=2022-06-19&project[contractType]=Billable&project[budget]=100

The API throws an error saying that project[status] is an invalid parameter The API docs give this within the curl example. You can see that the data for "project" is grouped:

title=Test folder&description=Test description&project={"ownerIds":["KUFK5PMF"],"startDate":"2021-10-19","endDate":"2021-10-26","contractType":"Billable","budget":100}

They're nesting the query into objects, I guess? How would I go about doing that with my PHP array? I tried a recursive function someone had done, but it didn't give me what it's looking for either.

Any help is appreciated! Thanks!

CodePudding user response:

The project parameter is JSON in their example, so use json_encode() to create that.

$folder_data = array(
    "title" => "Testing API Creation",
    "description" => "Testing the Wrike API by creating this folder.",
    "project" => json_encode(array(
        "status" => "OnHold",
        "startDate" => "2022-05-19",
        "endDate" => "2022-06-19",
        "contractType" => "Billable",
        "budget" => 100
    ))
);
  • Related