2014-01-24 20 views
0

我試圖給我的數據庫播種示例用戶。我希望每個用戶不要相同,但是我的代碼生成了10個相同的用戶。在推送到數組之前,如何構建循環以創建新的隨機用戶?如何在PHP中創建隨機用戶以種子數據庫

$frst = array('Bob','Joe','Kim','Gary','David','Vasili','Fred','Seaton','Steve','Lou','Greg'); 
$last = array('Jones','Allen','Darling','Foster','Johnson','Hall','Lynch','Wilson','Baldwin','Largent','Shelton','Porter'); 
$role = array('Architect','Electrical','General','Mechanical'); 
$rand_frst = array_rand($frst, 4); 
$rand_last = array_rand($last, 4); 
$rand_role = array_rand($role, 4); 

$users = []; 
$i = 1; 
    $user = [ 
    'first_name' => $frst[$rand_frst[0]], 
    'last_name' => $last[$rand_last[0]], 
    'email'  => $frst[$rand_frst[0]] . '@' . $last[$rand_last[0]] . '.com', 
    'password' => $last[$rand_last[0]], 
    'company_id' => rand(1, 5), 
    'username' => $frst[$rand_frst[0]] . $last[$rand_last[0]], 
    'zipcode' => rand(98101, 98999), 
    'role'  => $role[$rand_role[0]] 
    ]; 
while ($i <= 10) 
{ 
    array_push($users, $user); 
    $i++;    
}  


var_dump($users); 

我試圖把$用戶陣列while循環中,但我得到了相同的結果

+1

在循環中做你的隨機化。 –

回答

0

你總是試圖訪問[0]第一個返回數組值。你只有一次(循環之前)建立一個隨機選擇。這就是爲什麼你的價值觀與1-10相同。你需要在while循環內重新隨機化。

$frst = array('Bob','Joe','Kim','Gary','David','Vasili','Fred','Seaton','Steve','Lou','Greg'); 
$last = array('Jones','Allen','Darling','Foster','Johnson','Hall','Lynch','Wilson','Baldwin','Largent','Shelton','Porter'); 
$role = array('Architect','Electrical','General','Mechanical'); 
$users = array(); 
$i = 0; 
while ($i < 10) // no need to use <= since it will evaluate < first and stop 
{ 

    $rand_frst = array_rand($frst); // no idea why you wanted to select 4 by random, 
    $rand_last = array_rand($last); // when you're only using 1. so i've removed 
    $rand_role = array_rand($role); 

    $user = array(
    'first_name' => $frst[$rand_frst], 
    'last_name' => $last[$rand_last], 
    'email'  => $frst[$rand_frst] . '@' . $last[$rand_last] . '.com', 
    'password' => $last[$rand_last], 
    'company_id' => rand(1, 5), 
    'username' => $frst[$rand_frst] . $last[$rand_last], 
    'zipcode' => rand(98101, 98999), 
    'role'  => $role[$rand_role] 
    ); 
    array_push($users, $user); 
    $i++;    
} 



var_dump($users); 
+0

我得到NULL返回這個代碼,除了數字rand函數。而且我在循環中包含了$ frst,$ last和$ role vars。 –

+0

上面更新完整的代碼,對不起,我沒有拉過定義的數組,我們不再需要指定'[0]',因爲我們一次只能隨機抽取1個。 –

+1

你走了!在我嘗試使用while循環重構之前,我有10個這樣的'[0]'。好的眼睛,先生! –

相關問題