在开发网站的过程中,我们经常需要将字符串转换成对象数组,以方便对数据进行操作。在 PHP 中,有多种方法可以实现这个功能,本文将为大家介绍其中一种方法。
一、使用 json_decode 函数
PHP 中提供了 json_decode 函数,可以将 JSON 格式的字符串转换成对象或数组。下面是一个简单的示例:
1 2 3 4 5 | <?php
$str = '{ "name" : "Tom" , "age" : 18}';
$obj = json_decode( $str );
print_r( $obj );
?>
|
登录后复制
输出结果为:
1 2 3 4 5 | stdClass Object
(
[name] => Tom
[age] => 18
)
|
登录后复制
可以看到,json_decode 函数将 JSON 字符串转换成了一个名为 stdClass 的对象。
如果要将其转换成数组,可以在函数中加上第二个参数 true,如下所示:
1 2 3 4 5 | <?php
$str = '{ "name" : "Tom" , "age" : 18}';
$arr = json_decode( $str , true);
print_r( $arr );
?>
|
登录后复制
输出结果为:
1 2 3 4 5 | Array
(
[name] => Tom
[age] => 18
)
|
登录后复制
可以看到,json_decode 函数将 JSON 字符串转换成了一个关联数组。
二、将字符串按行分割并转换成数组
如果你的字符串不是 JSON 格式的,可以先将其按行分割,再逐行处理。下面是一个简单的示例:
1 2 3 4 5 6 7 8 9 10 11 12 | <?php
$str = "Tom,18\nJerry,22\n" ;
$arr = explode ( "\n" , $str );
foreach ( $arr as $item ) {
$tmp = explode ( "," , $item );
$result [] = array (
"name" => $tmp [0],
"age" => $tmp [1]
);
}
print_r( $result );
?>
|
登录后复制
输出结果为:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | Array
(
[0] => Array
(
[name] => Tom
[age] => 18
)
[1] => Array
(
[name] => Jerry
[age] => 22
)
)
|
登录后复制
可以看到,将字符串按行分割后,再逐行处理,转换成了一个包含多个对象的数组。
三、使用正则表达式
如果你的字符串格式比较复杂,或者需要对字符串进行更复杂的处理,可以使用正则表达式。下面是一个简单的示例:
1 2 3 4 5 6 7 8 | <?php
$str = "name=Tom&age=18&gender=male" ;
preg_match_all( "/(\w+)=([^&]+)/" , $str , $matches );
foreach ( $matches [1] as $key => $value ) {
$result [ $value ] = $matches [2][ $key ];
}
print_r( $result );
?>
|
登录后复制
输出结果为:
1 2 3 4 5 6 | Array
(
[name] => Tom
[age] => 18
[gender] => male
)
|
登录后复制
可以看到,使用正则表达式,将查询字符串转换成了一个关联数组。
以上是三种将字符串转换成对象数组的方法,读者可以根据实际情况选择合适的方法。
以上是php 字符串怎么转对象数组的详细内容。更多信息请关注PHP中文网其他相关文章!