【问题标题】:How to initialize multidimensional associative array with empty values如何用空值初始化多维关联数组
【发布时间】:2017-10-14 15:52:38
【问题描述】:

我想创建并初始化一个多维数组,其中包含已知可能的第二维键但没有值。

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

)

【问题讨论】:

    标签: php arrays multidimensional-array associative-array


    【解决方案1】:

    那时我通常会使用映射函数:

    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(),但我展示的是长版本,以防万一。

    【讨论】:

    • 这对我有用。我用$DataArray = array(array()); 初始化了数组,在数据填充之后为了删除索引0 处的第一个空子数组,我使用了unset($DataArray['0']);
    • 要初始化 $DataArray,您真正需要的是:$DataArray = array();。由于映射函数为您添加了具有空白值的辅助数组。这样你就不需要弹出 0 索引一个。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-01
    • 1970-01-01
    • 2015-05-12
    • 2011-07-28
    相关资源
    最近更新 更多