2013-04-20 82 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); 
相關問題