2017-10-14 147 views
0

我想創建並初始化一個多維數組,其中第二維但沒有值的已知可能鍵。如何使用空值初始化多維關聯數組

這個數組將存儲event_ids(動態填充)和每個event_id一個數組有四個不同的計數(也動態填充)。

結構,我想創建

Array 
(
    [0] => Array =================> This index will be the event_id 
     (
      [invitation_not_sent_count] => 
      [no_response_yet_count] => 
      [will_not_attend_count] => 
      [will_attend_count] => 
     ) 
) 

我做什麼這麼遠?

$DataArray = array(); 
$DataArray[] = array('invitation_not_sent_count' => '', 
             'no_response_yet_count' => '', 
             'will_not_attend_count' => '', 
             'will_attend_count' => ''); 

和環路內我填充數據動態地想:

$DataArray[$result->getId()]['no_response_yet_count'] = $NRCount; 

我得到的是:

Array 
(
[0] => Array 
    (
     [invitation_not_sent_count] => 
     [no_response_yet_count] => 
     [will_not_attend_count] => 
     [will_attend_count] => 
    ) 

[18569] => Array 
    (
     [no_response_yet_count] => 2 
    ) 

[18571] => Array 
    (
     [no_response_yet_count] => 1 
    ) 

我想的是,如果一個值在迭代中不可用,其條目應該在初始化時定義爲空。所以,如果所有其他罪名是除了no_response_yet_count數據空,數組應該是:

期望輸出

Array 
(
[18569] => Array 
    (
     [invitation_not_sent_count] => 
     [no_response_yet_count] => 2 
     [will_not_attend_count] => 
     [will_attend_count] => 
    ) 

[18571] => Array 
    (
     [invitation_not_sent_count] => 
     [no_response_yet_count] => 1 
     [will_not_attend_count] => 
     [will_attend_count] => 
    ) 

回答

0

我通常在這一點上再打一個映射函數:

function pre_map(&$row) { 
    $row = array 
    (
     'invitation_not_sent_count' => '', 
     'no_response_yet_count' => '', 
     'will_not_attend_count' => '', 
     'will_attend_count' => '' 
    ); 
} 

然後在while/for循環中:

{ 
    $id = $result->getId(); 
    if (!isset($DataArray[$id])) { pre_map($DataArray[$id]); } 
    $DataArray[$id]['no_response_yet_count'] = $NRCount; 
} 

if (!isset($DataArray[$id]))是爲了確保它不會清除相同的索引行,以防萬一您碰巧重新循環相同的ID。因此,它只會映射一次,然後永遠不會再循環。

還有一些其他的單行快捷方式,甚至可能使用array_map(),但我顯示的是長版本,爲了全面的靈活性,以防萬一。

+0

讓我試試這個 –

+0

對不起,在複製/粘貼時出現了一些語法錯誤... – IncredibleHat

+0

這對我來說確實有竅門。我使用'$ DataArray = array(array());'初始化數組,並在數據填充後刪除索引0處的第一個空子數組,我使用'unset($ DataArray ['0']);' –