我目前正在建立一个系统,用户可以将内容发布到桌面上,这会自动添加一个" Day - " .date(" N");发布到表格中的字符串,一旦发布一周,我将删除它。我已经完成了实现这一过程的后勤工作 - 无论何时用户添加帖子,它都会检查day.txt文件以查看当天是否是另一天,如果是,则运行以下功能:
// The function is quite simple in theory:
// Load the two lists as a string, convert to array
// Send code out removing all posts with a certain day.
function removeOldPosts(){
$newday = ':Day-'.date('N');
// I realise the below two lines are unefficient, I'll consolidate them later
$currentPosts = file_get_contents('list.txt');
$posts = explode(" ", $currentPosts);
while(($key = array_search($newday, $posts)) !== false){
unset($posts[$key]);
echo 'Unset a value: '.$key.'<br>';
}
echo ($posts); // Testing variables in array
$newPosts = implode(" ", $posts);
echo $newPosts;
file_put_contents('list.txt', $newPosts);
return;
}
然而,&#34; echos&#34;仍然显示为包含我要删除的值...我想知道是否有人在我的代码中发现错误 - 我假设我的while语句出错了,但是这个这是我第一次使用这样的声明,所以我不完全确定如何有效地找到包含当天的所有值,然后删除它们。
对于&#34; list.txt&#34;内容,看起来像
1:Spitfire:Day-4:8JX-UKR8:8JX-UKR8:Spirit:110 1:Spitfire:Day-4:8JX-UKR8:8JX-UKR8:Spirit:110 1:Spitfire:Day-4:8JX-UKR8:8JX-UKR8:Spirit:110 1:Spitfire:Day-4:8JX-UKR8:8JX-UKR8:Spirit:110 1:Spitfire:Day-4:8JX-UKR8:8JX-UKR8:Spirit:1101:Spitfire:Day-4:8JX-UKR8:8JX-UKR8:Spirit:110 1:Spitfire:Day-4:8JX-UKR8:8JX-UKR8:Spirit:110 1:Spitfire:Day-4:8JX-UKR8:8JX-UKR8:Spirit:110
非常感谢任何帮助!!!
答案 0 :(得分:1)
如果要清理数组,请尝试使用array_filter。此示例将删除所有带有':Day-4'子字符串的条目。
$currentPosts = '1:Spitfire:Day-4:8JX-UKR8:8JX-UKR8:Spirit:110 1:Spitfire:Day-5:8JX-UKR8:8JX-UKR8:Spirit:110 1:Spitfire:Day-6:8JX-UKR8:8JX-UKR8:Spirit:110 1:Spitfire:Day-3:8JX-UKR8:8JX-UKR8:Spirit:110 1:Spitfire:Day-4:8JX-UKR8:8JX-UKR8:Spirit:110 1:Spitfire:Day-4:8JX-UKR8:8JX-UKR8:Spirit:110 1:Spitfire:Day-5:8JX-UKR8:8JX-UKR8:Spirit:110 1:Spitfire:Day-4:8JX-UKR8:8JX-UKR8:Spirit:110';
$posts = explode( " ", $currentPosts );
$posts = array_filter( $posts, function( $item ) {
return strpos( $item, ':Day-4' ) === false;
});
print_r( $posts );