Skip to content

Instantly share code, notes, and snippets.

@wzul
Created November 1, 2023 11:30
Show Gist options
  • Save wzul/542b4d526cdef7f8723c35060947c31f to your computer and use it in GitHub Desktop.
Save wzul/542b4d526cdef7f8723c35060947c31f to your computer and use it in GitHub Desktop.
PHP Array same key for http_build_query
<?php
/**
* This is my first contribution in stack overflow!
* https://stackoverflow.com/questions/17161114/php-http-build-query-with-two-array-keys-that-are-same/77402243#77402243
*/
function http_build_query_duplicate_key( array $array ) {
$special_keys = [];
foreach($array as $key => $value) {
if (is_array($value) AND count($value) > 0) {
if (array_is_list($value)) {
foreach($value as $value_b) {
if (is_array($value_b) AND !array_is_list($value_b)) {
foreach($value_b as $key2 => $value2) {
$special_keys[] = http_build_query_duplicate_key([$key.'['.$key2.']' => $value2]);
}
} else {
$special_keys[] = http_build_query([$key => $value_b]);
}
}
} else {
$special_keys[] = http_build_query_duplicate_key([$key => [$value]]);
}
unset($array[ $key ]);
}
}
$and_symbol = '';
if (count($array) > 0) {
$and_symbol = '&';
}
return implode('&', $special_keys) . $and_symbol . http_build_query($array);
}
$feed_params = array(
'phone' => [
'brand' => [
'samsung' => [
'galaxy' => ['S21', 'S22', 'S23'],
],
'xiaomi' => [
'redmi' => ['note 3','note 4', 'note 5'],
'mi' => ['3','10'],
],
'poco' => [
'm' => ['3','4','5']
]
],
]
);
echo urldecode(http_build_query_duplicate_key($feed_params)) . PHP_EOL;
/** Output:
* phone[brand][samsung][galaxy]=S21&
* phone[brand][samsung][galaxy]=S22&
* phone[brand][samsung][galaxy]=S23&
* phone[brand][xiaomi][redmi]=note 3&
* phone[brand][xiaomi][redmi]=note 4&
* phone[brand][xiaomi][redmi]=note 5&
* phone[brand][xiaomi][mi]=3&
* phone[brand][xiaomi][mi]=10&
* phone[brand][poco][m]=3&
* phone[brand][poco][m]=4&
* phone[brand][poco][m]=5
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment