1

I am trying to create the following output with the PHP function http_build_query():

xyz[abc][]=someValue

So the first approach was as easy as it gets:

$params = ['xyz' => ['abc' => 'someValue']];

echo http_build_query($params); // Outputs: xyz[abc]=someValue (urlencoded ofc)

But I failed when I tried so many approaches to put the second [], that I am at a point where I do not know further. My plan is not to write a new function since I usually use PHP common functions as much as I can. But if it is not possible I am glad to see some possible solutions for my issue.

Thanks in advance :)!

6
  • 1
    ['xyz' => ['abc' => ['someValue'] ] ] should be sufficient? Edit: Nevermind it addes an index... Commented Jul 27, 2018 at 9:07
  • You should try ['some'Value'] Commented Jul 27, 2018 at 9:08
  • @Scuzzy No, because this would output xyz[abc][0]=someValue. I really need an empty array here, since the API that I am using requires that. Commented Jul 27, 2018 at 9:09
  • Then I'd suggest manual building of the string or post processing of the string. (Eg find and replace with a regex. Commented Jul 27, 2018 at 9:10
  • Well then you either will have to write your own function, or replace those [x]= occurrences back to just []= using a regular expression or something. (If you only ever needed one of those, then ['' => 'someValue'] would do the trick - PHP allows the empty string as an array key, but using that you could obviously not have more than one element in that array.) Commented Jul 27, 2018 at 9:11

1 Answer 1

3

Suggestion in regards to "post processing" of the string with preg_replace().

This looks for [n] and replaces it with []

$params = ['xyz' => ['abc' => ['someValue'] ] ];

$query = preg_replace( '/%5B\d+%5D/','%5B%5D', http_build_query( $params ) );

or

$params = ['xyz' => ['abc' => ['someValue'] ] ];

$query = urlencode( preg_replace( '/\[\d+\]/','[]', urldecode( http_build_query( $params ) ) ) );
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.