Parse query string into an array

前端 未结 10 2385
暖寄归人
暖寄归人 2020-11-22 02:58

How can I turn a string below into an array?

pg_id=2&parent_id=2&document&video 

This is the

相关标签:
10条回答
  • 2020-11-22 03:35

    For this specific question the chosen answer is correct but if there is a redundant parameter—like an extra "e"—in the URL the function will silently fail without an error or exception being thrown:

    a=2&b=2&c=5&d=4&e=1&e=2&e=3 
    

    So I prefer using my own parser like so:

    //$_SERVER['QUERY_STRING'] = `a=2&b=2&c=5&d=4&e=100&e=200&e=300` 
    
    $url_qry_str  = explode('&', $_SERVER['QUERY_STRING']);
    
    //arrays that will hold the values from the url
    $a_arr = $b_arr = $c_arr = $d_arr = $e_arr =  array();
    
    foreach( $url_qry_str as $param )
        {
          $var =  explode('=', $param, 2);
          if($var[0]=="a")      $a_arr[]=$var[1];
          if($var[0]=="b")      $b_arr[]=$var[1];
          if($var[0]=="c")      $c_arr[]=$var[1];
          if($var[0]=="d")      $d_arr[]=$var[1];
          if($var[0]=="e")      $e_arr[]=$var[1];
        }
    
        var_dump($e_arr); 
        // will return :
        //array(3) { [0]=> string(1) "100" [1]=> string(1) "200" [2]=> string(1) "300" } 
    

    Now you have all the occurrences of each parameter in its own array, you can always merge them into one array if you want to.

    Hope that helps!

    0 讨论(0)
  • 2020-11-22 03:43

    If you're having a problem converting a query string to an array because of encoded ampersands

    &
    

    then be sure to use html_entity_decode

    Example:

    // Input string //
    $input = 'pg_id=2&parent_id=2&document&video';
    
    // Parse //
    parse_str(html_entity_decode($input), $out);
    
    // Output of $out //
    array(
      'pg_id' => 2,
      'parent_id' => 2,
      'document' => ,
      'video' =>
    )
    
    0 讨论(0)
  • 2020-11-22 03:51

    You want the parse_str function, and you need to set the second parameter to have the data put in an array instead of into individual variables.

    $get_string = "pg_id=2&parent_id=2&document&video";
    
    parse_str($get_string, $get_array);
    
    print_r($get_array);
    
    0 讨论(0)
  • 2020-11-22 03:52

    This is one-liner for parsing query from current URL into array:

    parse_str($_SERVER['QUERY_STRING'], $query);
    
    0 讨论(0)
提交回复
热议问题