2011-07-23 58 views
3

我使用foreach循環來創建數據庫值的數組,像這樣:如何構建多維數組?

foreach ($query->result_array() as $row) { 
    array(
     'user_id' => $user_id, 
     'post_id' => $row['id'], 
     'time'  => '0', 
     'platform' => $platform 
    ); 
} 

比方說,我拉2行,我需要這個的foreach創建以下格式的多維數組:

$data = array(
    array(
     'user_id' => '12', 
     'post_id' => '37822', 
     'time'  => '0', 
     'platform' => 'email' 
    ), 
    array(
     'user_id' => '12', 
     'post_id' => '48319', 
     'time'  => '0', 
     'platform' => 'email' 
    ), 
); 

可能很簡單,只是仍然不能把它弄下來。謝謝。

+0

$ data [] = array(*你已經擁有*); – 2011-07-23 06:20:32

回答

4

你可以先聲明空數組:

$results = array(); 

然後,每次有新行的時候,將其添加到陣列:

$results[] = $row; 

也好,反正要添加任何東西到該數組:

$results[] = array(something here); 


在特定情況下,你會p robably使用這樣的事情:

$results = array(); 
foreach ($query->result_array() as $row) { 
    $results[] = array(
        'user_id' => $user_id, 
        'post_id' => $row['id'], 
        'time' => '0', 
        'platform' => $platform 
       ); 
} 


作爲參考,PHP手冊的相應部分:Creating/modifying with square bracket syntax