'11', 2 => '22', 3 => '33', 4"/> '11', 2 => '22', 3 => '33', 4">
Home > Backend Development > PHP Tutorial > 怎么让字符串和数组相互转换

怎么让字符串和数组相互转换

WBOY
Release: 2016-06-13 10:50:47
Original
855 people have browsed it

如何让字符串和数组相互转换
一个字符串如下:
{1:"11",2:"22",3:"33",4:"44",7:"77"}
想把以上字符串转换为这样的数组

array (
1 => '11',
2 => '22',
3 => '33',
4 => '44',
7 => '77',
)

就是1 2 3 4 7 这几个作为数组的索引 11 22 33 44 77 这几个作为数组的值 可以通过 $arr[2] 这样访问相对应的值

当对数组的值做了一些操作后 数组又变成了

array (
1 => '18',
2 => '20',
3 => '33',
4 => '44',
6 => '66',
7 => '77',
18 => '76',
)


这时又怎么把这个数组转换为这样的字符串:
{1:"18",2:"20",3:"33",4:"44",6:"66",7:"77",18:"76"}


------解决方案--------------------

PHP code
$s = '{1:"11",2:"22",3:"33",4:"44",7:"77"}';$s = preg_replace('/"?(\w+)"?/e', '"\"".trim("$1","\"")."\""', $s);print_r(json_decode($s, 1));<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