0

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]

3 Answers 3

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

and

var_dump($_GET);
Sign up to request clarification or add additional context in comments.

Comments

0

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' ) );
?>

2 Comments

looks like you also missed the word manually in bold! Useful function nonetheless, thanks
@Haroldo looks like I'm missing a lot today! :D I've updated the function..still useful?
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.