PHP 转换字符串为数组的 3 种方法
要将 PHP 字符串转换为数组,可以使用以下三种方法:
- 使用
explode()函数将字符串分割为数组
例如,将逗号分隔的字符串转换为数组:
$str = 'apple,banana,orange';
$arr = explode(',', $str);
print_r($arr);
输出:
Array
(
[0] => apple
[1] => banana
[2] => orange
)
- 使用
json_decode()函数将 JSON 字符串转换为数组
例如,将 JSON 字符串转换为数组:
$json = '{"name":"John","age":30,"city":"New York"}';
$arr = json_decode($json, true);
print_r($arr);
输出:
Array
(
[name] => John
[age] => 30
[city] => New York
)
- 使用
unserialize()函数将序列化的字符串转换为数组
例如,将序列化的字符串转换为数组:
$str = 'a:3:{i:0;s:5:"apple";i:1;s:6:"banana";i:2;s:6:"orange";}';
$arr = unserialize($str);
print_r($arr);
输出:
Array
(
[0] => apple
[1] => banana
[2] => orange
)
注意:以上方法仅适用于特定的数据格式。如果您的 PHP 数据不符合这些格式,则需要使用其他方法将其转换为数组。
原文地址: https://www.cveoy.top/t/topic/m7fe 著作权归作者所有。请勿转载和采集!