Created
August 9, 2012 08:26
-
-
Save dervn/3302309 to your computer and use it in GitHub Desktop.
随机取文件若干行
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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