如何将下面的字符串转换为数组?
pg_id=2&parent_id=2&document&video
这就是我要找的数组,
array(
'pg_id' => 2,
'parent_id' => 2,
'document' => ,
'video' =>
)
如何将下面的字符串转换为数组?
pg_id=2&parent_id=2&document&video
这就是我要找的数组,
array(
'pg_id' => 2,
'parent_id' => 2,
'document' => ,
'video' =>
)
当前回答
使用http://us1.php.net/parse_str
注意,它的用法是:
parse_str($str, &$array);
not
$array = parse_str($str);
请注意,以上内容仅适用于PHP 5.3及更早版本。在PHP 5.4中删除了调用时引用传递。
其他回答
如果您在将查询字符串转换为数组时遇到问题,因为已编码的&符号
&
然后确保使用html_entity_decode
例子:
// 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' =>
)
您需要parse_str函数,并且需要设置第二个参数,以便将数据放入数组中,而不是放入单个变量中。
$get_string = "pg_id=2&parent_id=2&document&video";
parse_str($get_string, $get_array);
print_r($get_array);
有时parse_str()单独是准确的,它可以显示如下:
$url = "somepage?id=123&lang=gr&size=300";
Parse_str()将返回:
Array (
[somepage?id] => 123
[lang] => gr
[size] => 300
)
最好像这样将parse_str()与parse_url()结合起来:
$url = "somepage?id=123&lang=gr&size=300";
parse_str( parse_url( $url, PHP_URL_QUERY), $array );
print_r( $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] =>
)