john
john

Reputation: 1273

how to filter the output of an array produced with a foreach loop

For reading all .txt files in a directory, i use code blow:

// Grab all the files from subscribers dir
$dir = 'subscribers/';
if ($dh = opendir($dir)) {
    while(($file = readdir($dh))!== false){
        if ($file != "." && $file != "..") { // This line strips out . & ..                                     
                $all_subscribers[] = $file;   // put all files in array 
        }
    }           
}
closedir($dh);
asort($all_subscribers);

Each txt file has 4 lines and looks like this:

id-12345678 // id
Friends // name of category
John // name subscriber
[email protected] // email subscriber

Output:

foreach($all_subscribers as $file) { 
    // open and prepare files
    $all_subscribers_files = 'subscribers/'.$file;          
    // get data out of txt file     
    $lines = file($all_subscribers_files, FILE_IGNORE_NEW_LINES); // set lines from all files into an array 
    $recipients_category = $lines[1];               
    $recipients_name = $lines[2]; //  name of recipients
    $recipients_email = $lines[3]; //  email of the recipients                  
    //$mail->AddCC($recipients_email, $recipients_name);                            
}

When i echo $recipients_email it shows me all the email-addresses form all subscribers.

When i echo $recipients_category, it shows me all the categories form each subscriber. I have 5 categories: Friends, Collegas, Family, Club and Offside

How can i strip out the emails corresponding to Offside category? So when i echo $recipients_email; it should give me all the email-addresses from all categories except from Offside category...

Upvotes: 0

Views: 61

Answers (2)

Progrock
Progrock

Reputation: 7485

You could filter as you go, or add each file array to one big collection and then filter as you like:

<?php
$collection =
[
    ['id-12345678', 'Friends', 'Luke', '[email protected]'],
    ['id-23456789', 'Enemy', 'Darth', '[email protected]']
];

$no_evil = array_filter($collection, function($item) {
    return $item[1] !== 'Enemy';
});

var_export($no_evil);

Output:

array (
    0 => 
    array (
      0 => 'id-12345678',
      1 => 'Friends',
      2 => 'Luke',
      3 => '[email protected]',
    ),
  )

Upvotes: 1

W Kristianto
W Kristianto

Reputation: 9303

If you need to collect all emails from all categories (except Offside) :

$results = [];

foreach ($all_subscribers as $file) {
    $all_subscribers_files = 'subscribers/' . $file;
    $lines                 = file($all_subscribers_files, FILE_IGNORE_NEW_LINES);

    // If category is not Offside
    if ($lines[1] != 'Offside') {
        // Collect email
        $results[] = $lines[3];
    }
}

var_dump($results);

Upvotes: 1

Related Questions