note 111158 deleted from function.http-build-query by googleguy

From: Date: Mon, 21 Jan 2013 12:37:11 +0000
Subject: note 111158 deleted from function.http-build-query by googleguy
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-193296@lists.php.net to get a copy of this message
Note Submitter: faesouza at outlook dot com ---- The http_build_query function does not implement properly the HTTP spec for array values. For: http_build_query(array('arr' => array('a', 'b'))); http_build_query gives you: arr[0]=a&arr[1]=b I have this simple function that implements the HTTP's expected format for the query string: buildQuery(array('arr' => array('a', 'b'))); Will give you: arr[]=a&arr[]=b As expected according to the HTTP spec. The helper function code is available below: function buildQuery(array $params, $parent = '') { $pairs = array(); foreach ($params as $key => $value) { if (!empty($parent)) { if (is_string($key)) { $key = $parent . '[' . urlencode($key) . ']'; } else { $key = $parent . '[]'; } } else { $key = urlencode($key); } if (is_string($value)) { $pairs[] = $key . '=' . urlencode($value); } elseif (is_numeric($value)) { $pairs[] = $key . '=' . $value; } elseif (is_array($value)) { $pairs[] = self::buildQuery($value, $key); } } return implode('&', $pairs); } PS: It would be possibly useful to have an level control in the recursion so we can avoid infinite looping. Best Regards, Fabrício José

« previous php.notes (#193296) next »