將文件資料打亂並顯示


因為 MSN 的朋友問了這個問題,當時都已經作了一次解釋,雖然他說自己試試看,不過最後我也在自己的好奇心推使下,又再寫了這簡單的程式,雖然方法有很多種,可是沒有多想的情況下就寫了這方法,不算得上是好吧..?

主要檔案 :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<?php
class randData {

var $data_file = '';

function getRandNum($data, $total) {
while($total > 0) {
$rid = array_rand($data);
unset($data[$rid]);
$total= count($data);
$temp[] = $rid;
$this->getRandNum($data, $total);
}
return $temp;
}

function show() {
$data = file($this->data_file);
$total= count($data);

$rand_num_list = $this->getRandNum($data, $total);

for($i=0; $i<$total; $i++) {
list($num, $name, $password) = explode('<>',$data[$rand_num_list[$i]]);
echo "$num => $name => $password <br />";
}
}

}

$o = new randData();
$o ->data_file = 'data.txt';
$o ->show();
?>

測試資料 :

1
2
3
4
1<>名稱<>密碼<>
2<>名稱<>密碼<>
3<>名稱<>密碼<>
4<>名稱<>密碼<>