| px | top | add code | search | signup | login | help |
<?php
//===============================================================================
// (c)2004 by M. Slack - GPL License.
// Build URL query strings from an array.
// The outer function is simply a 'wrapper' for the inner function. This allows for
// any setup and cleanup code before and after calling the inner function.
// Note that the input array is passed by *reference* as well as the query string being
// built. This is due to the recursive nature of the inner function that will walk
// through multidiminsional arrays.
//
// INPUT: array *BY REFERENCE* (multidiminsional is ok) of arguments.
// Hashes or numerically indexed arrays are cool. NOTE: keys that point to an array are
// *NOT* returned.
//
//
// RETURNS: query string in the format of key=value.
// A question mark (?) is prepended to the first argument and an ampersand (&)
// separates the arguments. Keys and arguments are URL encoded.
// The trailing ampersand is truncated in the outer function as I really
// did not want to complicate things in the inner, recursive, function.
//
// Tested to 6 levels deep - Take care with large datasets, might run out of memory.
//
function build_url_query(&$query_ary) { // Wrapper function.
function query_build(&$query_ary, &$query_string) { // Take down array.
foreach($query_ary as $key=>$value) {
if(is_array($value)) { // If we find an array in this
query_build($value, $query_string); // array element, call ourself
} // to walk that one - and so on.
else { // Start building query string
$query_string .= rawurlencode($key) . '=' . rawurlencode($value) . "&";
}
}
}
$query_string = '?'; // Starting value of query string.
query_build($query_ary, $query_string); // Call inner fcn here, not above.
return(rtrim($query_string, " \n\t\r&")); // Trim trailing whitespace and ampersand.
}
//==============================================================================
?>
Comments or questions?
PX is running PHP 5.2.11
Thanks to Miranda Productions for hosting and bandwidth.
Use of any code from PX is at your own risk.