如何将文件分配给作为文件一部分的元素数组

我有一个包含.txt文件的目录。在每个.txt文件中都是行,在彼此之下。第二行是类别行。一个 txt 文件如下所示:


id-12345678 // id line

sport // category line

应该从其他类别中排除几个类别名称,例如Offside和2019 我已经过滤了如下数组:


$blogfiles = glob("data/articles/*.txt"); // array with ALL blogfiles

$all_categories = array();


foreach($blogfiles as $blogfile) { // Loop through the blogfiles in the directory   

    $lines = file($blogfile, FILE_IGNORE_NEW_LINES); // all lines of the txt file into an array

    $all_categories[] = $lines[1]; // category line (2nd line in txt file)

    $excl_categories = array('Offside','2019'); // contains elements that should be excluded

    $filtered_categories = array_diff($all_categories,$excl_categories); //new filtered array of categories

我需要的是一个数组,blogfiles其中的类别已被过滤。我不知道如何将相应的博客文件绑定到过滤后的数组


慕尼黑的夜晚无繁华
浏览 142回答 1
1回答

达令说

用于in_array()测试每个类别,而不是array_diff()在整个数组上使用。$excl_categories = array('Offside','2019'); // contains elements that should be excluded$filtered_files = [];$filtered_categories = [];foreach($blogfiles as $blogfile) { // Loop through the blogfiles in the directory       $lines = file($blogfile, FILE_IGNORE_NEW_LINES); // all lines of the txt file into an array    $category = $lines[1]; // category line (2nd line in txt file)    if (!in_array($category, $excl_categories)) {        $filtered_categories[] = $category;        $filtered_files[] = $blogfile;    }}
打开App,查看更多内容
随时随地看视频慕课网APP