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

时间:2015-07-28 09:52:47

标签: php arrays multidimensional-array

我有以下数组:

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
    )
)

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

2 个答案:

答案 0 :(得分:1)

$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);

答案 1 :(得分:0)

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

$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;
        }
    }
}