PHP数组、字符串相互转换简单的实现方法

当把一个数组转换成一个字符串时,将会设置胶合符——将被插入到生成字符串中的数组值之间的字符或代码。

当把字符串转换成数组时,要指定分隔符,它用于标记什么应该变成独立数组元素。

$array = explode(separator,$string); 
$string = implode(glue,$array);

使用和理解这两个函数的关键之处是分隔符(separator)和胶合符(glue)关系。

字符串转换成数组 explode(separator,$string)

$source = "hello1,hello2,hello3,hello4,hello5"; // 按逗号分离字符串 
$hello = explode(',',$source);
for($index=0;$index<count($hello);$index++) {
	echo $hello[$index];echo "</br>"; 
}

数组转换成字符串 implode(glue,$array)

$dateArray = [
	2017,
	10,
	24
];
$dateString = implode('-', $dateArray);
echo $dateString;
© 版权声明
THE END

喜欢就支持一下吧

点赞0 分享