Parse query string into an array

前端 未结 10 2384
暖寄归人
暖寄归人 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!

提交回复
热议问题