2013-04-20 136 views
0

我正在为我的小型社交网络撰写一个“不友好”脚本,基本上这位不请自来的行为需要从他们的朋友列表中删除他们的名为$user的身份证,我的身份证号码为:$my_id。我已经制作了向每个用户文件添加用户标识的脚本,但我不知道如何删除它?使用fwrite从文本文档中删除特定数据?

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和他们的$user我的friend_list 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; 
    } 
} 
+0

我会强烈建议您存储移动到适当的数据库(并且你标记了mysql,这对于这类工作来说很好)。 – Ignas 2013-04-20 04:03:36

+0

我可以看到为什么你会这一天,虽然用于存储与用户有关的用户标识,并且不限制用户到“最大”的朋友,如果我想要使用每个说varchar,我将不得不使用,我会设置一个限制,并与int我不能有任何逗号。所以.csv文件在这种情况下工作正常,它是一个逗号分隔值文件,因此.csv – 2013-04-20 04:06:44

+0

然后,您应该阅读关于关系和外键。你可以创建一个新的表来存储友谊,比如:id,user_id,friend_id,date_friended等等。然后这将会更容易管理。 – Ignas 2013-04-20 04:09:49

回答

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);