2

我有 3 组具有不同元素编号的二维数组?一个是需要作为键(日期和时间)与其他两个数组进行比较的数组。另外两个数组必须按顺序排列。对于空的行,我想要设置为-9999。

第一个数组:

Array (   
       [0] => Array
          (
            [0] => 01/7/2013
            [1] => 12.00 a.m

          )

       [1] => Array
          (
            [0] => 01/7/2013
            [1] => 12.01 a.m

          )

       [2] => Array
          (
            [0] => 01/7/2013
            [1] => 12.02 a.m

          )

      )

对于第二个数组:

Array(   

   [0] => Array
       (
          [0] => 01/7/2013
          [1] => 12.01 a.m
          [2] => 9.02
       )
 )

对于第三个数组:

 Array(   
    [0] => Array
        (
            [0] => 01/7/2013
            [1] => 12.00 a.m
            [2] => 1.23
            [3] => 6.1
        )

    [1] => Array
        (
            [0] => 01/7/2013
            [1] => 12.02 a.m
            [2] => 1.75
            [3] => 1.75
        )

  )

我需要输出为:

Array(   
    [0] => Array
        (
            [0] => 01/7/2013
            [1] => 12.00 a.m
            [2] => -9999
            [3] => 1.23
            [4] => 6.1
        )

    [1] => Array
        (
            [0] => 01/7/2013
            [1] => 12.01 a.m
            [2] => 9.02
            [3] => -9999
            [4] => -9999
        )
    [2] => Array
        (
            [0] => 01/7/2013
            [1] => 12.02 a.m
            [2] => -9999
            [3] => 1.75
            [4] => 1.75
        )
 )
4

1 回答 1

3
$arr = array_merge($arr1, $arr2, $arr3);
$out = array();
$cnt = 0;
foreach ($arr as $key => $value){
    $date = explode('/', $value[0]);//Change date format
    $dex = strtotime($date[1].'/'.$date[0].'/'.$date[2].' '.$value[1]);
    $head = (array_key_exists($dex, $out)) ? $out[$dex] : array_slice($value, 0, 2);
    $out[$dex] = array_merge($head, array_slice($value, 2));
    $cnt = ($cnt > count($out[$dex])) ? $cnt : count($out[$dex]);
}
$out = array_map(function ($e) use ($cnt){
    return array_pad($e, $cnt, '-9999');
}, array_values($out));
print_r($out);

这适用于 PHP 5.3 及更高版本。对于旧版本的 PHP,您可以将array_map函数替换为以下内容:

foreach ($out as $key => $value){
    $res[] = array_pad($value, $cnt, -9999);
}
print_r($res);

新版本(适用于 PHP 5.3 或更高版本):

$template = array();
array_walk($arr1, function (&$e, $k) use (&$template){
    $date = explode('/', $e[0]);
    $dex = strtotime($date[1].'/'.$date[0].'/'.$date[2].' '.$e[1]);
    $template[$dex][0] = '-9999';
});
$arr1 = array_combine(array_keys($template), $arr1);
$out = array();
$data = array($arr2, $arr3);
foreach ($data as $key => $value){
    foreach ($value as $key2 => $value2){
        $date = explode('/', $value2[0]);//Change date format
        $dex = strtotime($date[1].'/'.$date[0].'/'.$date[2].' '.$value2[1]);
        $out[$key][$dex] = array_slice($value2, 2);
    }
    $out[$key] += array_diff_key($template, $out[$key]);
    foreach ($out[$key] as $key2 => $value2){
        $arr1[$key2] = array_merge($arr1[$key2], $value2);
    }
}
print_r(array_values($arr1));
于 2013-07-23T06:57:34.427 回答