PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, May 16, 2022

[FIXED] How to convert PHP multidimensional associative array to API http query in the format the API specifies?

 May 16, 2022     api, arrays, php, request     No comments   

Issue

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!


Solution

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
    ))
);


Answered By - Barmar
Answer Checked By - Robin (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing