*
* @param $array1 Array( String|Array )
* @param $array2 Array( String|Array )
+ * @param $prefix String
* @return String
*/
-function wfArrayToCGI( $array1, $array2 = null ) {
+function wfArrayToCGI( $array1, $array2 = null, $prefix = '' ) {
if ( !is_null( $array2 ) ) {
$array1 = $array1 + $array2;
}
if ( $cgi != '' ) {
$cgi .= '&';
}
+ if ( $prefix !== '' ) {
+ $key = $prefix . "[$key]";
+ }
if ( is_array( $value ) ) {
$firstTime = true;
- foreach ( $value as $v ) {
- $cgi .= ( $firstTime ? '' : '&') .
- urlencode( $key . '[]' ) . '=' .
- urlencode( $v );
+ foreach ( $value as $k => $v ) {
+ $cgi .= $firstTime ? '' : '&';
+ if ( is_array( $v ) ) {
+ $cgi .= wfArrayToCGI( $v, null, $key . "[$k]" );
+ } else {
+ $cgi .= urlencode( $key . "[$k]" ) . '=' . urlencode( $v );
+ }
$firstTime = false;
}
} else {
if ( is_object( $value ) ) {
$value = $value->__toString();
}
- $cgi .= urlencode( $key ) . '=' .
- urlencode( $value );
+ $cgi .= urlencode( $key ) . '=' . urlencode( $value );
}
}
}
* @return array Array version of input
*/
function wfCgiToArray( $query ) {
- if( isset( $query[0] ) && $query[0] == '?' ) {
+ if ( isset( $query[0] ) && $query[0] == '?' ) {
$query = substr( $query, 1 );
}
$bits = explode( '&', $query );
$ret = array();
- foreach( $bits as $bit ) {
- if( $bit === '' ) {
+ foreach ( $bits as $bit ) {
+ if ( $bit === '' ) {
continue;
}
list( $key, $value ) = explode( '=', $bit );
$key = urldecode( $key );
$value = urldecode( $value );
- $ret[$key] = $value;
+ if ( strpos( $key, '[' ) !== false ) {
+ $keys = array_reverse( explode( '[', $key ) );
+ $key = array_pop( $keys );
+ $temp = $value;
+ foreach ( $keys as $k ) {
+ $k = substr( $k, 0, -1 );
+ $temp = array( $k => $temp );
+ }
+ if ( isset( $ret[$key] ) ) {
+ $ret[$key] = array_merge( $ret[$key], $temp );
+ } else {
+ $ret[$key] = $temp;
+ }
+ } else {
+ $ret[$key] = $value;
+ }
}
return $ret;
}
wfArrayToCGI(
array( 'baz' => 'AT&T', 'ignore' => '' ),
array( 'foo' => 'bar', 'baz' => 'overridden value' ) ) );
+ $this->assertEquals(
+ "path%5B0%5D=wiki&path%5B1%5D=test&cfg%5Bservers%5D%5Bhttp%5D=localhost",
+ wfArrayToCGI( array(
+ 'path' => array( 'wiki', 'test' ),
+ 'cfg' => array( 'servers' => array( 'http' => 'localhost' ) ) ) ) );
+ }
+
+ function testCgiToArray() {
+ $this->assertEquals(
+ array( 'path' => array( 'wiki', 'test' ),
+ 'cfg' => array( 'servers' => array( 'http' => 'localhost' ) ) ),
+ wfCgiToArray( 'path%5B0%5D=wiki&path%5B1%5D=test&cfg%5Bservers%5D%5Bhttp%5D=localhost' ) );
}
function testMimeTypeMatch() {