一、函数讲解
1、explode()函数 把字符串打散为数组:
2、implode()函数 把数组元素组合为字符串:
(详细讲解见下文 三)
例如:
<?php
$str = '107_lab_2017';
$array=explode('_', $str);//以下划线为分隔符将字符串打散为数组
print_r($array);
echo implode('_', $array);//以下划线为分隔符将数组合并成字符串
?>
执行结果为:
Array | |
( | |
[0] => 107 | |
[1] => lab | |
[2] => 2017 | |
) | |
107_lab_2017 |
二、实战用法
在实际项目中,例如添加好友和关注等用来保存好友和关注的人的id
比如 id为1的用户添加了id为2, 3, 4, 5, 6这5个用户为好友。可以在用户表中加一个friends字段 (为防止因好友过多导致超出字段长度限制 这里直接给friends一个text类型),
id为1用户的好友可以字符串2_3_4_5_6的形式保存在friends字段中
如果需要判断id为1的用户是否添加过id为num(Ps:num代表一个数字,为某个用户的id)的用户为好友 可以从数据库中取出friends字段将其打散为数组判断num是否在数组中。
例如:
<?php
$con = mysqli_connect('localhost', 'root', '123456', 'tdbank');
if(mysqli_connect_errno($con)){
die('Could not connect:'.mysqli_error());
}
$sql = 'SELECT friends from users WHERE id=1';
$result = mysqli_query($con, $sql);
$row = mysqli_fetch_assoc($result);
$id_array=explode('_', $row['friends']);
if(!isset($_GET['id']) || !is_numeric($_GET['id'])){
echo '用户不存在';
exit;
}
//判断是否已经添加过id为$_GET['id']的用户为好友
if(in_array($_GET['id'], $id_array)){
echo '你们已经是好友了';
}else{
$friends = empty($row['friends'])?$_GET['id']:$row['friends'].'_'.$_GET['id'];
$sql = 'UPDATE users set friends = '."'{$friends}'".' WHERE id = 1';
echo '<br>'.$sql;
$status = mysqli_query($con, $sql);
if($status){
echo '好友添加成功';
}else{
echo '好友添加失败';
}
}
?>
三、详细讲解
1、语法规则: explode(separator, string, limit);
参数 | 描述 |
---|---|
separator | 必需。规定在哪里分割字符串。 |
string | 必需。要分割的字符串。 |
limit | 可选。规定所返回的数组元素的数目。 可能的值:
|
版本细则:
返回值: | 返回字符串的数组 |
PHP 版本: | 4+ |
更新日志: | 在 PHP 4.0.1 中,新增了 limit 参数。在 PHP 5.1.0 中,新增了对负数 limit 的支持。 |
2、语法规则: implode(separator,array)
参数 | 描述 |
---|---|
separator | 可选。规定数组元素之间放置的内容。默认是 ""(空字符串)。 |
array | 必需。要组合为字符串的数组。 |
版本细则:
返回值: | 返回由数组元素组合成的字符串。 |
PHP 版本: | 4+ |
更新日志: | 在 PHP 4.3.0 中,separator 参数变成可选的。 |