2016-11-18 102 views
0

我需要做一個DB惰性的,看起來像這樣:PHP推維數組

DB::table('users')->insert([ 
    ['email' => '[email protected]', 'votes' => 0], 
    ['email' => '[email protected]', 'votes' => 0] 
]); 

但我tryint建立與例如在一個循環的動態值的數據添加更多的時間:

array_push($a,'email' => $this->mail,'votes' => $this->votes); 

所以,我可以簡單地以後運行此:

DB::table('users')->insert($myData); 

所以,我怎麼能推維數組?

+0

你到底在做什麼?你能展示結構嗎? – ggderas

回答

1

如果我正確理解你的問題。你可以做簡單的做到這些,你可以把你的陣列原始數組所以它會創建一個多元數組。

$a = array(); 
    array_push($a,array('email' => $this->mail,'votes' => $this->votes)); 
+1

哦,那就是我搞砸了,我忘了數組( – user2636197

0

你可以這樣做:

$array = []; 

    $dataComingFromSomewhere = []; // Assuming this is your data source 

    for($index = 0; $index < count($dataComingFromSomewhere); $index++) 
    { 
     $newUserArray = ['email' => $dataComingFromSomewhere[$index]->email, 'votes' => $dataComingFromSomewhere[$index]->votes]; 
     array_push($array, $newUserArray); 
    } 

    DB::table('users')->insert($array); 
0

眼前這個

$myData[]= array('email' => $this->mail,'votes' => $this->votes); 
DB::table('users')->insert($myData); 
0

使用不當的array_push()。推一個關聯元素,它是這樣的:

$a['email'] = $this->mail; $a['votes'] = $this->votes; 

或做到這一點:

$a = array_merge($a, array('email' => $this->mail, 'votes' => $this->votes)); 
0

首先初始化$a爲空數組$a = array()

然後換行

array_push($a,'email' => $this->mail,'votes' => $this->votes); 

array_push($a,array('email' => $this->mail,'votes' => $this->votes)); 

,你可以做,

DB::table('users')->create($a);