从两个索引数组中加入类似数据

时间:2015-10-21 18:59:14

标签: php

我必须以这种方式将两个数组合并为一个:第一个数组中的'v'字段应该保存为结果数组中的'v1'字段,来自第二个数组的同名字段 - 作为'v2',但是与相同的't'字段分组。所有't'字段必须是不同的并且有序。

例如:

$a1 = array(
  0 => array('v' => '13','t' => '2015-09-08 18:50:00'),
  1 => array('v' => '25','t' => '2015-09-08 19:00:00'),
  2 => array('v' => '34','t' => '2015-09-08 19:05:00'),
  3 => array('v' => '24','t' => '2015-09-08 19:10:00'));

$a2 = array(
  0 => array('v' => '10','t' => '2015-09-08 18:50:00'),
  1 => array('v' => '29','t' => '2015-09-08 18:55:00'),
  2 => array('v' => '17','t' => '2015-09-08 19:00:00'));

/* ... */

$result = array(
  0 => array('v1' => '13','v2' => '10','t' => '2015-09-08 18:50:00'),
  1 => array('v1' => null,'v2' => '29','t' => '2015-09-08 18:55:00'),
  2 => array('v1' => '25','v2' => '17','t' => '2015-09-08 19:00:00'),
  3 => array('v1' => '34','v2' => null,'t' => '2015-09-08 19:05:00'),
  4 => array('v1' => '24','v2' => null,'t' => '2015-09-08 19:10:00'));

请注意,'t'日期以5分钟为增量,但每个数组不一定包含每个区间的值(可能存在随机间隙)。

阵列足够大(> 30,000)。你能帮我制作一个有效的算法(更少的代码)吗?提前谢谢!

1 个答案:

答案 0 :(得分:1)

这应该非常有效:

$final = [];
$a1 = array_map(function($a) { return ['v1' => $a['v'], 't' => $a['t']] }, $a1);
$a2 = array_map(function($a) { return ['v2' => $a['v'], 't' => $a['t']] }, $a2);
$a = $a1 + $a2;
foreach($a as $el) {
    $timestamp = $el['t'];
    if (!isset($final[$timestamp])) {
        $final[$timestamp] = ['v1' => null, 'v2' => null];
    }
    $final[$timestamp] = array_merge($final[$timestamp], $el);
}
usort($final, function($a, $b) {
    return strtotime($a['t']) - strtotime($b['t']);
}); 

如果您使用的是较旧版本的PHP,则需要使用[]更改任何数组声明为array()