我正在为我的迷你社交网络写一个"unfriend"脚本,基本上unfriend动作需要从他们的朋友列表中删除他们的id: $user
和我的id: $my_id
。我已经制作了将用户id添加到每个用户文件的脚本,但我不确定如何删除这个?
我的friend_list
文件:1,2,3 // I am user 1
其friend_list
文件:1,2,3 // They are user 3
我目前使用这个来添加每个id到文本文件:
if($action === 'accept'){
mysql_query("DELETE FROM `friend_req` WHERE `from`='$user' AND `to`='$my_id'");
$fp = fopen($user_data['friend_list'], 'a');
fwrite($fp, ",".$user."");
fclose($fp);
$their_id = friend_list_from_user_id($user);
$fp = fopen($their_id, 'a');
fwrite($fp, ",".$my_id."");
fclose($fp);
}
但是要从他们的friend_list
和他们的$user
id从我的friend_list
中删除$my_id
,我想我需要使用这样的东西,但它不起作用:
if($action === 'unfriend'){
$fp = fopen($user_data['friend_list'], 'a');
unset($user);
fclose($fp);
$their_id = friend_list_from_user_id($user);
unset($my_id);
fclose($fp);
}
但是这似乎不起作用,我应该怎么做才能从相应的文件中只删除指定的用户名?
哦,还有,这可能有用,也可能没用:
$myFile = $file;
$fh = fopen($myFile, 'r');
$theData = fgets($fh);
fclose($fh);
$friend = explode(',', $theData);
for($i=0; $i < count($friend); $i++){
if($i >= 0)
{
if($friend[$i] == $user_id) {
$their_user_id = $user_id;
}
}
要解决您的问题,只需这样做:
//get the contents of the file
$contents = file_get_contents($user_data['friend_list']);
$contents = str_replace(",".$friend_id, "", $contents); //remove the friend's id
//open the file again and rewrite the whole thing with the new contents without that id
$fp = fopen($user_data['friend_list'], 'w+');
fwrite($fp, $contents);
fclose($fp);