如何使用空值初始化多维关联数组

问题描述:

我想创建并初始化一个多维数组,其中第二维但没有值的已知可能键。如何使用空值初始化多维关联数组

这个数组将存储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] => 
    ) 

我通常在这一点上再打一个映射函数:

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']);' –