Skip to content
Advertisement

how to assign a file to an array of elements which are part of the file

I have a directory which contains .txt files. In each .txt files are lines, under each other. the 2nd line is the category line. A txt file looks like this:

id-12345678 // id line
sport // category line

A couple of categorynames should be excluded form the other categories, like Offside and 2019 I have filtered the array like below:

$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

What i need is an array of blogfiles in which the categories have been filtered in. I do not know how i can bind the corresponding blogfiles to the filtered array

Advertisement

Answer

Use in_array() to test each category, rather than using array_diff() on the whole array.

$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;
    }
}
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement