Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using implode to output numbered list from array?

I've been trying to figure this out for a couple hours now, but as a PHP newbie I'm struggling to wrap my head around it.

I am trying to pass multiple (numbered) items to an Amazon API. My array ($asins) is filled with all the stings I need.

Here's my array:

$asins = array('STRING_1', 'STRING_2', 'STRING_3');

I need to output in the following format:

ASINList.ASIN.1=STRING_1&ASINList.ASIN.2=STRING_2&ASINList.ASIN.3=STRING_3

The array will always contain 25 of these strings.

I realise this is probably incredibly simple, but any hints would be appreciated. I like to learn!

like image 339
Daniel Crocker Avatar asked Jul 22 '26 09:07

Daniel Crocker


1 Answers

This code should done it. Array key always start at '0'. in you case, you need '1'

$array = array('STRING_1', 'STRING_2', 'STRING_3');
$URLparameters = array();

foreach( $array as $key => $value ){
    $newkey = $key + 1;
    $URLparameters[] = "ASINList.ASIN.".$newkey."=".$value;
}

$result = implode("&", $URLparameters);

[EDIT] based on the idea of Emiliano Sangoi

$a = array('ASINList.ASIN.1', 'ASINList.ASIN.2', 'ASINList.ASIN.3');
$b = array('STRING_1', 'STRING_2', 'STRING_3');
$c = array_combine($a, $b);

echo http_build_query($c);
like image 65
Pierre-André Vullioud Avatar answered Jul 25 '26 01:07

Pierre-André Vullioud



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!