我有一个csv表(我的csv文件http://jpst.it/1GCd9)
| id | email | name | google.com | yahoo.com |
| 1 | email1@email.com | jack | | + |
| 2 | email2@email.com | jack | + | |
| 3 | email3@email.com | jack | | |
能否获得列名带有“ +”的电子邮件?
例如,我想指定google.com并收到电子邮件email2@email.com
我只知道如何通过列ID:(
while (($row = fgetcsv($fileHandle, 0, ",")) !== FALSE) {
if($flag) { $flag = false; continue; }
$explode = explode(";",$row[4]);
echo $explode[4]. ", ";
}
答案 0 :(得分:2)
通过使用经过清理的CSV(删除所有多余的空白和数组过滤器,您可以获得所需的内容。
我使用array_map('trim', array_filter(explode($delimeter, $lines[0]), function($entry){return !empty($entry);}));
清除了空格中的所有输入,并在最后一个竖线字符处丢弃了结尾处的“空”标头。
请参阅以下功能:array_map,trim,array_filter。
然后,当一切都“标准化”时,我们将获得具有正确字段的关联数组数组,因此我们可以再次使用array_filter进行搜索。变量$only_with_plus
将仅包含与搜索参数匹配的关联数组。
$only_with_plus = array_filter($entries, function($entry) {
return $entry['google.com'] == '+' && $entry['email'] = 'email2@email.com';
});
在线查看:https://ideone.com/ZDn2dv
<?php
$CSV = <<<EOF
| id | email | name | google.com | yahoo.com |
| 1 | email1@email.com | jack | | + |
| 2 | email2@email.com | jack | + | |
| 3 | email3@email.com | jack | | |
EOF;
$delimeter = '|';
$lines = explode("\n", $CSV);
$key_names = array_map('trim', array_filter(explode($delimeter, $lines[0]), function($entry){return !empty($entry);}));
$entries = [];
$len = count($lines);
for($c = 1; $c < $len; $c++) {
$line = array_map('trim', array_filter(explode($delimeter, $lines[$c]), function($entry){return !empty($entry);}));
$entry = [];
foreach($line as $key => $value) {
$entry[$key_names[$key]] = $value;
}
$entries[] = $entry;
}
$only_with_plus = array_filter($entries, function($entry) {
return $entry['google.com'] == '+' && $entry['email'] = 'email2@email.com';
});
var_dump($only_with_plus);
// your code goes here
答案 1 :(得分:1)
您不能直接过滤csv,但是可以在将其解析为数组后进行过滤;
http://sandbox.onlinephpfunctions.com/code/f17969e35fcfc5e2f4b2f25202359f1b4cc4840b