字串處理成數組的問題
一個字串如下:
$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);
------解決方案--------------------
再來二種
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);
------解決方案--------------------
添塊磚
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)*/
------解決方案--------------------
PHP code[User:root Time:14:14:44 Path:/home/liangdong/php]$ php arr.php 1234[User:root Time:14:14:45 Path:/home/liangdong/php]$ cat arr.php