0

我正在为我的迷你社交网络编写一个“取消朋友”脚本,基本上取消朋友操作需要$user从他们的朋友列表中删除他们的 id call: 和我的 id call: $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);
}

但是要从我$my_id的他们friend_list和他们的$userid中删除,friend_list我想我需要使用这样的东西,但它不起作用:

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;
    }
}
4

1 回答 1

0

要解决您的问题,只需执行以下操作:

//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);
于 2013-04-20T04:29:05.730 回答