Skip to content

Instantly share code, notes, and snippets.

@dervn
Created August 9, 2012 08:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dervn/3302309 to your computer and use it in GitHub Desktop.
Save dervn/3302309 to your computer and use it in GitHub Desktop.
随机取文件若干行
<?php
$file_name = "7";
$out = $file_name.".out";
$num = 3000;
$lines = get_lines_random( $file_name, $num);
foreach($lines as $key=>$value) {
file_put_contents($out, $value, FILE_APPEND);
file_put_contents($out, "\n", FILE_APPEND);
}
function get_lines_random( $filename, $lines_num ) {
if( !file_exists($filename) ){
return false;
}
$ret = array();
$__tmp_ret= array();
$data = file($filename); //将文件存放在一个数组中;
$num = count($data); //条数;
for ( $i=0; $i < $lines_num; $i++ ) {
$id = mt_rand(0, $num-1); //随机数字;
if( !in_array($id, $__tmp_ret) ) {
array_push($__tmp_ret, $id);
$text = chop($data[$id]); //显示第几行数据,并去除空格;
$ret[$id] = $text;
} else {
$i--;
}
}
return $ret;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment