意外通知:null时未定义的索引

时间:2013-05-08 02:50:33

标签: symfony command-line-interface php

我写了一个小脚本,应该创建一个看起来像这样的数组:

array(1 => array( 'month'  => 'Jan',
                  'salary' => '01/31/2013',
                  'bonus'  => '02/15/2013'),
      2 => array('month' => '',...));

你得到了基本的想法:主数组中的索引是月(数字),每个都包含一个动态填充的数组。 month密钥取决于用户请求的语言,工资和奖金分配了工资和/或奖金的支付日期。到目前为止没有惊喜。

为了获得该数组的基本结构,我认为这将是最简单的:

$this->months = array_fill_keys(range(1,12), array( 'month' => null,
                                                    'salary' => null,
                                                    'bonus' => null));

然后我填充数组,事情一直运行顺利,直到我想将数据写入文件的位置,我喜欢这样:

private function writeFile()
{
    foreach($this->months as $key => $vals)
    {
        if ($vals['month'] === null)
        {//Only filled from date x to date y, some months can be empty
            continue;
        }
        //this seems to raise notices?
        if ($vals['salary'] === null)
        {
            $vals['salary'] = 'Does not apply';
        }
        fwrite($this->file, implode(',', $vals).PHP_EOL);
    }
    fclose($this->file);
    return $this;
}

我检查salary是否为空的行引发注意:“警告:未定义的索引工资”。目前我不得不将其添加到代码中:

if (!array_key_exists('salary', $vals) || $vals['salary'] === null)
{
    if (!array_key_exists('bonus', $vals) || $vals['bonus'] === null)
    {
        break;
    }
    $vals['salary'] = 'Does not apply';
}

获得我需要的结果。我用谷歌搜索了这个,偶然发现了this bug report,这是4年前(2009-05-08)的最后一次修改,但状态仍然是“没有反馈”。 有没有其他人遇到类似的故障/错误?或者我在这里遗漏了什么?如果没有<{1}}和函数调用而不需要更改我的设置if,我怎么能避免这个问题呢。

顺便说一句:我在Slackware 14上运行PHP 5.4.7。对于这个小应用程序,我使用了2个Symfony组件(ClassLoader和Console),但由于这是一个与之无关的对象的一部分Symfony,除了通过E_STRICT | E_ALL加载之外我不认为这是相关的。
由于该bug被认为是UniversalClassLoader相关的:是的,我使用的是PDO,但是在另一个类中。

2 个答案:

答案 0 :(得分:0)

我不确定,但尝试使用

$this->months = array_fill(1,12, array( 'month' => null,
                                                    'salary' => null,
                                                    'bonus' => null));

答案 1 :(得分:0)

经过几次var_dump后,我发现原因是什么:数组键是range(1,12),以确定我正在处理的是哪个月。为此,我以下列方式使用DateTime对象:

$date->modify('+ '.$diff.' days');
$key = $date->format('m');

问题是format调用返回一个字符串。目标是列出何时支付工资和奖金。如果15日是星期六或星期日,则必须每15日或下周三支付奖金。薪水应在当月的最后一天或上周五支付。
换句话说,奖金支付日期的分配如下:

$key = $date->format('m');
$this->months[$key]['month'] = $date->format('M');
if ($date->format('d') == 15)
{
    //find find week-day (15th or following Wednesday)
    $this->months[--$key]['bonus'] = $date->format('m/d/Y');
    $key++;
    //set date to end of month
}
//check week-day, and modify date if required
$this->months[$key]['salary'] = $date->format('m/d/Y');

因为$this->months数组的键是数字的,但是用于$key的格式是一个2位数的字符串,带有前导零,我遇到了问题。
每个月的第15个月,$key值被强制转换为整数(递减/递增运算符),但月份是使用字符串分配的。

我在原始问题中提供的信息不足,对不起,但我刚刚投入了一个全能的信息。修复,最后很容易:

$key = (int) $date->format('m');//cast

我真诚地感谢所有回复,以及为SO社区做出贡献的每个人。我会删除这个问题,但如果没有人反对,我想我可能会留下它作为我愚蠢的见证。