11, [bb] => 22, [cc] =>"/> 11, [bb] => 22, [cc] =>">

字符串处理成数组的有关问题

WBOY
Release: 2016-06-13 13:28:52
Original
832 people have browsed it

字符串处理成数组的问题
一个字符串如下:
$str = "aa:1,bb:2,cc:3,dd:4";


有两个要求:

1、我想把这个字符串拆分成一个数组,其中 aa、bb、cc、dd 为索引 11,22,33,44 分别为索引的值 如$arr = Array ( [aa] => 11, [bb] => 22, [cc] => 33, [dd] => 44 ) ,要怎么弄

2、要把这个字符串拆分成4个变量,变量名动态生成为 aa、bb、cc、dd 分别对应值为 11,22,33,44 这个要怎么操作?

------解决方案--------------------
两种方法:
1、

PHP code
$str = "aa:1,bb:2,cc:3,dd:4";
parse_str(preg_replace(array('/\w+/', '/:/','/,/'), array('"$0"','=','&'), $str), $ar);
print_r($ar);
<br><font color="#e78608">------解决方案--------------------</font><br>再来二种<br>
Copy after login
PHP code
$str = "aa:1,bb:2,cc:3,dd:4";
foreach(array_chunk(preg_split('/[:,]/', $str), 2) as $t) $ar[$t[0]] = $t[1];
print_r($ar);
<br><font color="#e78608">------解决方案--------------------</font><br>添块砖<br><br>
Copy after login
PHP code

$str = "aa:1,bb:2,cc:3,dd:4";
preg_replace("#([\w]+):([\d]+)#e", "\$arr['\\1']=\\2\\2", $str);

print_r($arr);
/*
Array
(
    [aa] => 11
    [bb] => 22
    [cc] => 33
    [dd] => 44
)

*/
<br><font color="#e78608">------解决方案--------------------</font><br>
Copy after login
PHP code
[User:root Time:14:14:44 Path:/home/liangdong/php]$ php arr.php 
1
2
3
4
[User:root Time:14:14:45 Path:/home/liangdong/php]$ cat arr.php 
<?php $str = "aa:1,bb:2,cc:3,dd:4";
$arr = explode(',', $str);
foreach ($arr as $val) {
        $fields = explode(':', $val);
        $key = trim($fields[0]);
        $val = trim($fields[1]);
        $res[$key] = $val;
}
extract($res);
for ($ch = ord('a'); $ch <= ord('d'); ++ $ch) {
        $key = str_repeat(chr($ch), 2);
        echo $$key . PHP_EOL;
}
?> <div class="clear">
                 
              
              
        
            </div>
Copy after login
Related labels:
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 Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template