【问题标题】:how to filter the output of an array produced with a foreach loop如何过滤使用 foreach 循环生成的数组的输出
【发布时间】:2019-12-19 16:33:16
【问题描述】:

为了读取目录中的所有.txt 文件,我使用代码打击:

// 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);

每个 txt 文件有 4 行,如下所示:

id-12345678 // id
Friends // name of category
John // name subscriber
john.smith@gmail.com // email subscriber

输出:

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);                            
}

当我回显$recipients_email 时,它会显示所有订阅者的所有电子邮件地址。

当我回显$recipients_category 时,它会显示每个订阅者的所有类别。 我有 5 个类别:Friends, Collegas, Family, Club and Offside

如何去除Offside 类别对应的电子邮件? 所以当我echo $recipients_email; 它应该给我所有类别的所有电子邮件地址,除了Offside 类别......

【问题讨论】:

  • 你为什么不为此使用数据库?
  • 这是一个简单的脚本,因此我想把它放在像 .txt 文件这样的平面文件数据库中
  • 相信我,从经验中吸取教训。文本文件是做这么简单的事情的大量工作。数据库将帮助您解决此问题,并使维护变得更加容易。

标签: php arrays file foreach


【解决方案1】:

如果您需要收集所有类别的所有电子邮件(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);

【讨论】:

  • 太棒了!非常简单的解决方案,但我想不出...
【解决方案2】:

您可以随时过滤,或者将每个文件数组添加到一个大集合中,然后根据需要进行过滤:

<?php
$collection =
[
    ['id-12345678', 'Friends', 'Luke', 'skywalker@example.com'],
    ['id-23456789', 'Enemy', 'Darth', 'vader@example.com']
];

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

var_export($no_evil);

输出:

array (
    0 => 
    array (
      0 => 'id-12345678',
      1 => 'Friends',
      2 => 'Luke',
      3 => 'skywalker@example.com',
    ),
  )

【讨论】:

    猜你喜欢
    • 2014-02-13
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-15
    • 1970-01-01
    • 2018-02-25
    相关资源
    最近更新 更多