Haroldo
Haroldo

Reputation: 37377

Manually write a url query string containing nested array data

I'm looking to manually write a multidimensional $_GET query string, saw this done the other day, but can't quite remember it!

something like:

www.url.com?val1=abc&val2=cde&[val3=fgh&val4=ijk]

Upvotes: 0

Views: 554

Answers (3)

mickmackusa
mickmackusa

Reputation: 48031

Rely on http_build_query() to perfectly format a query string for you.

Either use it directly in your script to generate the substring after ? in the url or use a sandbox to set up your array data, call the function, then copy-paste the output in your static file.

Code: (Demo)

$array = [
    'indexed value',
    'foo' => 'first level value',
    'bar' => ['baz' => 'second level']
];

echo http_build_query($array);
// 0=indexed+value&foo=first+level+value&bar%5Bbaz%5D=second+level

A fringe case consideration

Upvotes: 0

Bailey Parker
Bailey Parker

Reputation: 15903

Since array parameters in URL's are postfixed by brackets, I'd try a function like this:

    <?php
function array_map_scope( $callback, array $array, array $arguments = array(), $scope = array() ) {
    if( !is_callable( $callback ) ) {
        return( false );
    }
    $output = array();

    foreach( $array as $key => $value ) {
        if( is_array( $value ) ) {
            $output[$key] = array_map_scope( $callback, $value, $arguments, array_push_value( $scope, $key ) );
        } else {
            $output[$key] = call_user_func_array( $callback, array_merge( array( $value, array_push_value( $scope, $key ) ), $arguments ) );
        }
    }
    return( $output );
}

function array_push_value( $array, $value ) {
    $array[] = $value;
    return( $array );
}

function urlParam( $value, $key, $name ) {
    return( $name.'['.implode( array_map( 'urlencode', $key ), '][' ).']='.urlencode( $value ) );
}

function array_values_recursive( $array ) {
    $output = array();    
    foreach( $array as $value ) {
        if( is_array( $value ) ) {
            $output = array_merge( $output, array_values_recursive( $value ) );
        } else {
            $output[] = $value;
        }
    }
    return( $output );
}

function array2URL( $name, $array ) {
    $array = array_map_scope( 'urlParam', $array, array( urlencode( $name ) ) );
    return( implode( array_values_recursive( $array ), '&' ) );
}

echo array2URL('test', array( 'a'=>'a','b'=>array('ba'=>'ba','bb'=>'bb'),'c'=>'c' ) );
?>

Upvotes: 0

zerkms
zerkms

Reputation: 255055

http://domain.tld/path/to/script.php?arr[a][b][c]=foo

and

var_dump($_GET);

Upvotes: 5

Related Questions