* NameList.php
<?php
/**
* Created by PhpStorm.
* User: Mch
* Date: 9/24/18
* Time: 4:11 PM
*/
class NameList {
private $handle = null;
public function __construct($file) {
$this->handle = fopen($file, 'rb');
if ($this->handle === false) {
throw new Exception('open file '.$file.' error');
}
}
public function getYieldRows($length=256, $delimiter=' ') {
while (feof($this->handle) === false) {
yield fgetcsv($this->handle, $length, $delimiter);
}
}
public function getListRows($length=256, $delimiter='', $col=0) {
$list = new SplDoublyLinkedList();
if ($col === 0) {
$this->forEachLine(function($line) use ($list) {
$list->push($line);
}, $length);
} else {
$this->forEachLine(function($line) use ($list, $delimiter, $col) {
$fields = explode($delimiter, $line);
$list->push( $fields[$col-1] );
}, $length);
}
return $list;
}
private function forEachLine(callable $handler, $length=256) {
while (feof($this->handle) === false) {
$line = fgets($this->handle, $length);
call_user_func($handler, $line);
}
}
public function __destruct() {
fclose($this->handle);
}
public static function getRandom(SplDoublyLinkedList $list, int $n) : Array {
$pick = [];
while ($n-->0) {
$i = rand(0, $list->count() - 1);
array_push($pick, $list->offsetGet($i));
$list->offsetUnset($i);
}
return $pick;
}
}
<?php
/**
* Created by