Parse query string into an array

前端 未结 10 2383
暖寄归人
暖寄归人 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:27

    Use http://us1.php.net/parse_str

    Attention, it's usage is:

    parse_str($str, &$array);
    

    not

    $array = parse_str($str);
    
    0 讨论(0)
  • 2020-11-22 03:28

    Using parse_str().

    $str = 'pg_id=2&parent_id=2&document&video';
    parse_str($str, $arr);
    print_r($arr);
    
    0 讨论(0)
  • 2020-11-22 03:29

    There are several possible methods, but for you, there is already a builtin parse_str function

    $array = array();
    parse_str($string, $array);
    var_dump($array);
    
    0 讨论(0)
  • 2020-11-22 03:29

    This is the PHP code to split query in mysql & mssql

    enter code here
    function splitquery($strquery)
    {
    $arrquery=explode('select',$strquery);
    
    $stry='';$strx='';
    
    for($i=0;$i<count($arrquery);$i++)
    {
    if($i==1)
    {
        echo 'select '.trim($arrquery[$i]);
    }
    elseif($i>1)
    {
    
    $strx=trim($arrquery[($i-1)]);
    
        if(trim(substr($strx,-1))!='(')
        {
            $stry=$stry.'
    
    select '.trim($arrquery[$i]);
        }
        else
        {
            $stry=$stry.trim('select '.trim($arrquery[$i]));
        }
    
    $strx='';
    }
    } 
    
    return $stry;
    }
    

    Example:

    Query before

    select xx from xx select xx,(select xx) from xx where y=' cc' select xx from xx left join ( select xx) where (select top 1 xxx from xxx) oder by xxx desc ";

    Query after

    select xx from xx

    select xx,(select xx) from xx where y=' cc'

    select xx from xx left join (select xx) where (select top 1 xxx from xxx) oder by xxx desc

    Thank you, from Indonesia Sentrapedagang.com

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

    You can use the PHP string function parse_str() followed by foreach loop.

    $str="pg_id=2&parent_id=2&document&video";
    parse_str($str,$my_arr);
    foreach($my_arr as $key=>$value){
      echo "$key => $value<br>";
    }
    print_r($my_arr);
    
    0 讨论(0)
  • 2020-11-22 03:33

    Sometimes parse_str() alone is note accurate, it could display for example:

    $url = "somepage?id=123&lang=gr&size=300";
    

    parse_str() would return:

    Array ( 
        [somepage?id] => 123 
        [lang] => gr 
        [size] => 300 
    )
    

    It would be better to combine parse_str() with parse_url() like so:

    $url = "somepage?id=123&lang=gr&size=300";
    parse_str( parse_url( $url, PHP_URL_QUERY), $array );
    print_r( $array );
    
    0 讨论(0)
提交回复
热议问题