Home > php教程 > php手册 > body text

php操作字符串转换成数组

WBOY
Release: 2016-06-06 20:09:47
Original
1012 people have browsed it

今天在php论坛中看到以为朋友发了一个帖子请教php如何把字符串转换成数组;作为php程序员的新一第一反应是联想到explode(),implode()这两个函数。新一也是用里面的函数进行转换成数组的。 con[1]=28selt[1]=1con[2]=29selt[2]=4con[3]=26selt[3]=4 con[4]=30s

今天在php论坛中看到以为朋友发了一个帖子请教php如何把字符串转换成数组;作为php程序员的新一第一反应是联想到explode(),implode()这两个函数。新一也是用里面的函数进行转换成数组的。

con[1]=28&selt[1]=1&con[2]=29&selt[2]=4&con[3]=26&selt[3]=4

&con[4]=30&selt[4]=2&con[5]=4&selt[5]=1&con[6]=11&con[7]=12

上面就是网友需要转换成PHP数组的字符串;下面也是新一提供PHP转换代码

<?php $str = 'con[1]=28&selt[1]=1&con[2]=29&selt[2]=4&con[3]=26&selt[3]=4&con[4]=30&selt[4]=2&con[5]=4&selt[5]=1&con[6]=11&con[7]=12';
$arr = explode('&',$str);
$arr2 = array();
foreach($arr as $k=>$v){
        $arr = explode('=',$v);
        $arr2[$k] = $arr[1];
}
print_r($arr2);
?>
//输出
Array
(
    [0] => 28
    [1] => 1
    [2] => 29
    [3] => 4
    [4] => 26
    [5] => 4
    [6] => 30
    [7] => 2
    [8] => 4
    [9] => 1
    [10] => 11
    [11] => 12
)
//第二个
<?php $str = 'con[1]=28&selt[1]=1&con[2]=29&selt[2]=4&con[3]=26&selt[3]=4&con[4]=30&selt[4]=2&con[5]=4&selt[5]=1&con[6]=11&con[7]=12';
$arr = explode('&',$str);
$arr2 = array();
foreach($arr as $k=>$v){
        $arr = explode('=',$v);
        $arr2[$arr[0]] = $arr[1];
}
print_r($arr2);
?>
//输出
Array
(
    [con[1]] => 28
    [selt[1]] => 1
    [con[2]] => 29
    [selt[2]] => 4
    [con[3]] => 26
    [selt[3]] => 4
    [con[4]] => 30
    [selt[4]] => 2
    [con[5]] => 4
    [selt[5]] => 1
    [con[6]] => 11
    [con[7]] => 12
)
Copy after login

新一的PHP代码也可以解决字符串转换成数组的问题。最后phper网友应该在手册上面查到了parse_str()函数就可以把字符串转换成PHP数组;下面介绍一下parse_str()函数的说明让自己在脑子中好有印象.
parse_str() 函数把查询字符串解析到变量中。

parse_str(string,array)
string:需要转换的字符串;
array:返回到一个数组中;
如果没有设置array的话就覆盖同名变量
Copy after login
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!