Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

php url query nested array with no index

I'm working with a third party API that receives several parameters which must be encoded like this:

text[]=Hello%20World&text[]=How%20are%20you?&html[]=<p>Just%20fine,%20thank%20you</p>

As you can see this API can accept multiple parameters for text, and also for HTML (not in the sample call).

I have used http_build_query to correctly build a query string for other APIs

$params['text'][] = 'Hello World';
$params['text'][] = 'How are you?';
$params['html'][] = '<p>Just fine, thank you</p>';

$http_query = http_build_query($params);

The problem with this approach is that it will build a query string with the numeric index:

text[0]=Hello%20World&text[1]=How%20are%20you?&html[0]=<p>Just%20fine,%20thank%20you</p>

unfortunately the API I'm working with doesn't like the numeric index and fails.

Is there any php function/class-method that can help me build a query like this quickly?

Thank you

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I don't know a standard way to do it (I think there is no such way), but here's an ugly solution:

Since [] is encoded by http_build_query, you may generate string with indices and then replace them.

preg_replace('/(%5B)d+(%5D=)/i', '$1$2', http_build_query($params));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...