在每个PHP数组中具有相同数量的值



我有以下数组:

Array
(
[0] => Array
    (
        [data] => Array
            (
                [0] => 2015-07-21
                [1] => 2015-07-22
                [2] => 2015-07-23
                [3] => 2015-07-24
            )
    )
[1] => Array
    (
        [name] => 3389 Remote Desktop
        [data] => Array
            (
                [2015-07-21] => 37
                [2015-07-22] => 21
                [2015-07-23] => 38
                [2015-07-24] => 14
            )
    )
[2] => Array
    (
        [name] => 80 HTTP
        [data] => Array
            (
                [2015-07-21] => 22
                [2015-07-22] => 2
                                   // <- here is missing [2015-07-23] => 0
                                   // <- here is missing [2015-07-24] => 0
            )
    )
[4] => Array
    (
        [name] => 21 FTP
        [data] => Array
            (
                                   // <- here is missing [2015-07-21] => 0                                         
                [2015-07-22] => 1
                [2015-07-23] => 20
                                   // <- here is missing [2015-07-24] => 0
            )
    )
)

添加缺失的元素可以实现什么功能?到目前为止,我已经有了以下内容:

$newarray = array();
$count = count($arr[0][data]);
foreach($arr as $key => $subarr) {
    for ($i = 1; $i <= $count; $i++) {
        if (in_array($i, $subarr)) $newarray[$key][$i - 1] = $i;
        else $newarray[$key][$i - 1] = 0;
    }
}

部分地起作用并给出:

Array
(
[0] => Array
    (
        [0] => 0
        [1] => 0
        [2] => 0
        [3] => 0
    )
[3389 Remote Desktop] => Array
    (
        [0] => 0
        [1] => 0
        [2] => 0
        [3] => 0
    )
[80 HTTP] => Array
    (
        [0] => 0
        [1] => 0
        [2] => 0
        [3] => 0
    )
[21 FTP] => Array
    (
        [0] => 0
        [1] => 0
        [2] => 0
        [3] => 0
    )
)

,但我需要与初始数组具有完全相同的结构。欢迎任何帮助

$res = [$array[0]];
// make  default array with all zeros
$default = array_combine($array[0]['data'], array_fill(0,count($array[0]['data']),0));
// make new array changing default values with present
for($i = 1; $i < count($array); $i++ ) 
  $res[] = ['name' => $array[$i]['name'], 
            'data' => array_replace($default, $array[$i]['data'])];
print_r($res);

如果您总是在第一个元素上定义所有日期,那么您可以这样做:

$data = array(); // your array
$allDates = $data[0]['data'];
for($i=1; $i<count($data); $i++)
{
    foreach($allDates as $reqDate)
    {
        if(!array_key_exists($reqDate, $data[$]['data'])
        {
            $data[$]['data'][$reqDate] = 0;
        }
    }
}

相关内容

  • 没有找到相关文章