mattmezza / line-map
为每行文本执行操作
3.0.1
2018-03-21 11:09 UTC
Requires
- php: ^7.0
Requires (Dev)
- phpunit/phpunit: ^6.5
This package is auto-updated.
Last update: 2024-09-17 09:59:02 UTC
README
通过文件的行映射函数,逐行映射
使用composer require mattmezza/line-map
进行安装
使用方式如下
$map = Map\CSV::fileNamed("example.csv"); $rows = $map->with(function ($row, $idx) { return array_merge([$idx + 1], $row); })->get(); $header = $map->getHeader();
或
Map\Txt::fileNamed("lines.txt")->with(function ($line, $idx) { echo "$idx: $line"; });
TXT
// the callback function - can be also an anonymous closure $doStuff = function($line, $lineNumber) { return $lineNumber . ": " . $line; }; // from a string variable $text = "line 1 line2 line3"; $newLines = Map\Txt::string($text)->with($doStuff)->toArray(); // from a filename $filename = "./somelines.txt"; $newLines = Map\Txt::fileNamed($filename)->with($doStuff)->toArray(); // from a file resource handle $file = fopen($filename, "r"); $newLines = Map\Txt::file($file)->with($doStuff)->toArray();
CSV
// the callback function - can be also an anonymous closure $doStuff = function($row, $lineNumber, $headers) { echo $row[$headers[0]]; return $row; }; // from a string variable $csv = "name,surname John,Doe Foo,Bar"; $newRows = Map\CSV::string($csv)->with($doStuff)->toArray(); // from a filename $filename = "./somedata.csv"; $newRows = Map\CSV::fileNamed($filename)->with($doStuff)->toArray(); // from a file resource handle $file = fopen($filename, "r"); $newRows = Map\CSV::file($file)->with($doStuff)->toArray();
示例
快速遍历此CSV
name,username,email
Matt,mattmezza,mattmezza@gmail.com
对于每行生成自定义消息,使用以下模板替换值
Hello {{name}},
your username is {{username}}.
将每条消息发送给正确的用户并收集一些日志
$tpl = "Hello __name__, your username is __username__."; $logs = Map\CSV::fileNamed("file.csv")->with(function($row, $idx, $headers) use ($tpl) { $msg = $tpl; foreach ($headers as $header) { $msg = str_replace("{{".$header."}}", $row[$header], $msg); } return sendMail($row["email"]); })->toArray();