数组填充缺少的索引

时间:2014-06-13 05:47:01

标签: php arrays

有一个显示具有相同eid的数组的代码,其中包含一个天数数组

foreach ($data['display'] as $item) {
             $eid = implode($data['data'][$i]['eid']);
            $date = date('Y-m',strtotime($item['date_d'][0]));
            if (!isset($groups[$eid])) {
                $groups[$eid] = array(
                    'employeeId' => $eid,
                    'efullname' => $item['fullname'][0],
                    'hrsdiff' => $item['hrsdiff'][0],
                    'days' => array(
                        $date => $item['key'][0],
                    )
                );
            } else {
                @$groups[$eid]['days'][$date] += $item['key'][0];
            }
            $i++;
        }

显示:

[0] => Array
        (
            [employeeId] => 21
            [efullname] => MANOGURA EDGAR
            [hrsdiff] => 2.2331
            [days] => Array
                (
                    [2014-02] => 23
                    [2014-03] => 26
                    [2014-04] => 23
                )

        )

[1] => Array
        (
            [employeeId] => 1
            [efullname] => IBARDOLAZA VIRGILIO
            [hrsdiff] => 5.0333
            [days] => Array
                (
                    [2014-01] => 2
                    [2014-02] => 24
                    [2014-03] => 26
                    [2014-04] => 26
                )

        )

想要让days数组具有相同的索引,如果缺少它将添加缺失的索引天数,并且索引[0]中的值必须为0 ex天数数组应具有[2014-01] => 0

1 个答案:

答案 0 :(得分:0)

假设有两个数组,其中任何一个都缺少了键:

$a = array('2014-02' => 'afoo', '2014-03' => 'abar', '2014-04' => 'abaz');
$b = array('2014-02' => 'bfoo', '2014-03' => 'bbar', '2014-01' => 'bbaz');

$a += array_fill_keys(array_keys(array_diff_key($b, $a)), 0);
$b += array_fill_keys(array_keys(array_diff_key($a, $b)), 0);

print_r($a);
print_r($b);

输出:

Array
(
    [2014-02] => afoo
    [2014-03] => abar
    [2014-04] => abaz
    [2014-01] => 0
)
Array
(
    [2014-02] => bfoo
    [2014-03] => bbar
    [2014-01] => bbaz
    [2014-04] => 0
)