Skip to content

Instantly share code, notes, and snippets.

@salim523
Created February 5, 2021 17:04
Show Gist options
  • Save salim523/953016e29e4a34ab616b939ae01dbf48 to your computer and use it in GitHub Desktop.
Save salim523/953016e29e4a34ab616b939ae01dbf48 to your computer and use it in GitHub Desktop.
<?php
$params = array(
'key1' => array( 'k1v1', 'k1v2'),
'key2' => array( 'k2v1', 'k2v2'),
'key3' => array( 'k3v1', 'k3v2'),
);
function query_param_map( array $input_arr )
{
// declare output var
$output = array();
// intput array is not array so return empty array
if( !is_array( $input_arr ) ) return $output;
// keep count of object
$obj_i = 0;
// loop over object and it's values
foreach ($input_arr as $key => $values) {
// declare temp output
$temp_output = array();
// loop over values of given key
for ( $i = 0; $i < count( $values ); $i++ ) {
// first key output
if( 0 === $obj_i ){
$temp_output[] = sprintf( "%s=%s", $key, $values[ $i ] );
}
// other keys output
else{
// loop over output and append new key value into temp_output
for ($j=0; $j < count( $output ); $j++) {
$temp_output[] = sprintf( "%s&%s=%s", $output[ $j ], $key, $values[ $i ] );
}
}
}
// incress the index of the object
$obj_i++;
// copy the temp output into the output
$output = $temp_output;
}
// return the output
return $output;
}
$output = query_param_map( $params );
print_r( $output );
@salim523
Copy link
Author

salim523 commented Feb 5, 2021

Output:

Array
(
    [0] => key1=k1v1&key2=k2v1&key3=k3v1
    [1] => key1=k1v2&key2=k2v1&key3=k3v1
    [2] => key1=k1v1&key2=k2v2&key3=k3v1
    [3] => key1=k1v2&key2=k2v2&key3=k3v1
    [4] => key1=k1v1&key2=k2v1&key3=k3v2
    [5] => key1=k1v2&key2=k2v1&key3=k3v2
    [6] => key1=k1v1&key2=k2v2&key3=k3v2
    [7] => key1=k1v2&key2=k2v2&key3=k3v2
)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment