如何将下面的字符串转换为数组?

pg_id=2&parent_id=2&document&video 

这就是我要找的数组,

array(
    'pg_id' => 2,
    'parent_id' => 2,
    'document' => ,
    'video' =>
)

当前回答

你可以试试下面的代码:

<?php
    $str = "pg_id=2&parent_id=2&document&video";
    $array = array();
    parse_str($str, $array);
    print_r($array);
?>

输出:

Array
(
    [pg_id] => 2
    [parent_id] => 2
    [document] =>
    [video] =>
)

其他回答

有几个可能的方法,但对你来说,已经有一个内置的parse_str函数:

$array = array();
parse_str($string, $array);
var_dump($array);

这是在MySQL和SQL Server中拆分查询的PHP代码:

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;
}

例子:

查询前

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";

查询后

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

你可以试试下面的代码:

<?php
    $str = "pg_id=2&parent_id=2&document&video";
    $array = array();
    parse_str($str, $array);
    print_r($array);
?>

输出:

Array
(
    [pg_id] => 2
    [parent_id] => 2
    [document] =>
    [video] =>
)

这是一个从当前URL解析查询到数组的单行程序:

parse_str($_SERVER['QUERY_STRING'], $query);

。使用的作用是:将字串符

$str = 'pg_id=2&parent_id=2&document&video';
parse_str($str, $arr);
print_r($arr);