Converting a querystring into an associative array

前端 未结 5 901
刺人心
刺人心 2020-12-30 21:18

In PHP, I need a function to convert a querystring from an URL, say: http://example.com?key1=value1&key2=value2 into a PHP associative array : array [

相关标签:
5条回答
  • 2020-12-30 21:34
    foreach ($_GET as $key => $value) $arr["$key"]= $value;
    
    0 讨论(0)
  • 2020-12-30 21:40

    You can get just the atributes from a URL using parse_url()

    Once you have that you can use parse_str() to convert them to variables, it works with multidimensional arrays too!

    $str = "first=value&arr[]=foo+bar&arr[]=baz";
    
    parse_str($str, $output);
    echo $output['first'];  // value
    echo $output['arr'][0]; // foo bar
    echo $output['arr'][1]; // baz
    
    0 讨论(0)
  • 2020-12-30 21:44
    $url = 'http://example.com?key1=value1&key2=value2&key3=value3';
    
    preg_match_all('/\w+=.*/',$url,$matches);
    
    parse_str($matches[0][0], $output);
    
    print_r($output);
    
    0 讨论(0)
  • 2020-12-30 21:50

    Try using parse_url

    0 讨论(0)
  • 2020-12-30 21:57

    If you mean as what you written then it is very simple and don't need anything else there is a predefined Superglobal variable $_GET in PHP which itself represents all the query string as key, value pairs associative array.

    Example:

    // current page URI: http://localhost/test.php?key1=value1&key2=value2
    
    echo '<pre>';
    print_r($_GET);
    echo '</pre>';
    

    Result:

    Array(
        [key1] = value1
        [key2] = value2
    )
    

    For more information about $_GET PHP superglobal goto: http://php.net/manual/en/reserved.variables.get.php

    0 讨论(0)
提交回复
热议问题