它两个迭代器总是排序的,你可以缓存它们,每次迭代比较哪个先出现(如果不相等)并处理那个。如果相等,则同等处理。
不相等:
$it1[[period] => 04/04/2012 16:00:00] > $it2[[period] => 04/04/2012 15:00:00]
=> process $it2 data:
[period] => 04/04/2012 15:00:00
[bl_avg] => 5
[bl_full] => 0
as current():
[period] => 04/04/2012 15:00:00
[bl_subs] => 1
[bl_unsubs] => 1
[bl_avg] => 5
[bl_full] => 0
[bl_block_total] => 1
+ $it2->next();
注意:我不知道源数据 ( $it2[0] (15:00)
) [bl_subs => 1]
中不存在[bl_unsubs] => 1
的元素是如何[bl_block_total] => 1
来的。那是默认值吗?
相等:(跳过一次迭代)
$it1[[period] => 04/04/2012 17:00:00] == $it2[[period] => 04/04/2012 17:00:00]
=> process $it1 and $it2 data:
$it1:
[period] => 04/04/2012 17:00:00
[bl_subs] => 1
[bl_unsubs] => 2
[bl_block_total] => 0
$it2:
[period] => 04/04/2012 17:00:00
[bl_avg] => 0
[bl_full] => 7
as current():
[period] => 04/04/2012 17:00:00
[bl_subs] => 1
[bl_unsubs] => 2
[bl_avg] => 0
[bl_full] => 7
[bl_block_total] => 0
+ $it1->next(); $it2->next();
您可以将此处理包装成Iterator
它自己的,以便很好地封装。由于给出的信息有限,我创建了一个简化的示例,将日期缩短到问题的域:一次迭代两个迭代器。如果两个迭代器相等,则返回两者。如果不相等,则返回两者比较时的第一个。
使用的简化数据:
$ar1 = array('04/04/2012 16:00:00', '04/04/2012 17:00:00', '04/04/2012 18:00:00', '04/04/2012 19:00:00', '04/04/2012 20:00:00');
$ar2 = array('04/04/2012 15:00:00', '04/04/2012 17:00:00', '04/04/2012 18:00:00');
只有两个包含比较值的数组。这些变成了两个迭代器:
$it1 = new ArrayIterator($ar1);
$it2 = new ArrayIterator($ar2);
写出的问题仅限于两个迭代器。为了更通用地解决问题,它应该使用 0 个或更多迭代器。因此,每次迭代都会根据迭代器的当前值相互比较迭代器。为此,使用了比较功能。您可以将其与usort
Docs的工作方式进行比较:一个函数比较 A 和 B 并基于两者返回一个整数值:
- A < B:-1(A小于B,返回值小于零)
- A = B:0(A等于B,返回值为零)
- A > B:1(A大于B,返回值大于零)
这允许相互比较无限数量的对。它只需要两个函数:一个从我们使用的迭代器中获取当前值,另一个在 A 和 B 之间进行实际比较(实际上您可以将两者合并到一个函数中,但这是示例性的,您的数组/迭代器有点不同,我认为值得分开,这样你以后可以更容易地修改它)。所以首先是从迭代器中获取值的函数,我与 ISO 日期时间值进行比较,因为我可以用一个简单的方法来做到这一点strcmp
:
/**
* Get Comparison-Value of an Iterator
*
* @param Iterator $iterator
* @return string
*/
$compareValue = function(Iterator $iterator) {
$value = $iterator->current();
sscanf($value, '%d/%d/%d %s', $month, $day, $year, $timeISO);
$dateISO = sprintf('%04d-%02d-%02d %s', $year, $month, $day, $timeISO);
return $dateISO;
};
注意:我不知道您使用哪种日期格式,也许我将月份与日期混合在一起,只是交换变量,它几乎是自描述的。
这个函数所做的只是获取一个可以从迭代器中轻松比较的值。这还没有进行上面描述的比较,所以需要另一个函数来使用这个比较值函数作为依赖:
/**
* Compare two Iterators by it's value
*
* @param Iterator $a
* @param Iterator $b
* @return int comparison result (as of strcmp())
*/
$compareFunction = function(Iterator $a, Iterator $b) use ($compareValue) {
return strcmp($compareValue($a), $compareValue($b));
};
这就是现在的比较函数,基于strcmp
字符串比较函数并使用该$compareValue
函数获取字符串进行比较。
因此,假设您有一个包含两个迭代器的数组,现在可以对其进行排序。也可以将第一个元素与下一个元素进行比较,以确定它们是否相等。
完成后,现在可以创建一个由多个迭代器组成的迭代器,并且在每次迭代时,附加的迭代器都会被排序,并且只有第一个迭代器(以及与其相等的迭代器)将作为当前迭代器返回并转发。像这样的流程:
源
由于排序已经通过比较函数完成,所以只需要封装这个迭代逻辑。由于排序适用于任何大小(0 个或更多元素)的数组,因此它已经被通用化了。使用示例:
/**
* Usage
*/
$it = new MergeCompareIterator($compareFunction, array($it1, $it2));
foreach ($it as $index => $values) {
printf("Iteration #%d:\n", $index);
foreach ($values as $iteratorIndex => $value) {
printf(" * [%d] => %s\n", $iteratorIndex, $value);
}
}
此用法示例将输出它所在的迭代以及该迭代的关联值。在这种情况下,仅作为示例数组的时间信息仅由这些组成。它还把它来自的迭代器放在方括号中(0 表示第一个,1 表示第二个)。这会生成以下输出:
Iteration #0:
* [1] => 04/04/2012 15:00:00
Iteration #1:
* [0] => 04/04/2012 16:00:00
Iteration #2:
* [0] => 04/04/2012 17:00:00
* [1] => 04/04/2012 17:00:00
Iteration #3:
* [0] => 04/04/2012 18:00:00
* [1] => 04/04/2012 18:00:00
Iteration #4:
* [0] => 04/04/2012 19:00:00
Iteration #5:
* [0] => 04/04/2012 20:00:00
如您所见,对于两个(预排序的)迭代器中相等的比较值,将作为一对返回。在您的情况下,您需要进一步处理这些值,例如在提供默认值的同时合并它们:
$defaults = array('bl_subs' => 0, ...);
foreach ($it as $values) {
array_unshift($values, $default);
$value = call_user_func_array('array_merge', $values);
}
所以这实际上是 that 的用法MergeCompareIterator
。实现相当简单,到目前为止,这个没有缓存排序/当前迭代器,如果你想改进它,我把它留作练习。
完整代码:
<?php
/**
* @link http://stackoverflow.com/q/10024953/367456
* @author hakre <http://hakre.wordpress.com/>
*/
$ar1 = array('04/04/2012 16:00:00', '04/04/2012 17:00:00', '04/04/2012 18:00:00', '04/04/2012 19:00:00', '04/04/2012 20:00:00');
$ar2 = array('04/04/2012 15:00:00', '04/04/2012 17:00:00', '04/04/2012 18:00:00');
$it1 = new ArrayIterator($ar1);
$it2 = new ArrayIterator($ar2);
/**
* Get Comparison-Value of an Iterator
*
* @param Iterator $iterator
* @return string
*/
$compareValue = function(Iterator $iterator)
{
$value = $iterator->current();
sscanf($value, '%d/%d/%d %s', $month, $day, $year, $timeISO);
$dateISO = sprintf('%04d-%02d-%02d %s', $year, $month, $day, $timeISO);
return $dateISO;
};
/**
* Compare two Iterators by it's value
*
* @param Iterator $a
* @param Iterator $b
* @return int comparison result (as of strcmp())
*/
$compareFunction = function(Iterator $a, Iterator $b) use ($compareValue)
{
return strcmp($compareValue($a), $compareValue($b));
};
/**
* Iterator with a comparison based merge-append strategy over 0 or more iterators.
*
* Compares 0 or more iterators with each other. Returns the one that comes first
* and any additional one that is equal to the first as an array of their current()
* values in this current().
* next() forwards all iterators that are part of current().
*/
class MergeCompareIterator implements Iterator
{
/**
* @var Iterator[]
*/
private $iterators;
/**
* @var callback
*/
private $compareFunction;
/**
* @var int
*/
private $index;
/**
* @param callback $compareFunction (same sort of usort()/uasort() callback)
* @param Iterator[] $iterators
*/
public function __construct($compareFunction, array $iterators = array())
{
$this->setCompareFunction($compareFunction);
foreach ($iterators as $iterator) {
$this->appendIterator($iterator);
}
}
/**
* @param callback $compareFunction
*/
public function setCompareFunction($compareFunction)
{
if (!is_callable($compareFunction)) {
throw new InvalidArgumentException('Compare function is not callable.');
}
$this->compareFunction = $compareFunction;
}
public function appendIterator(Iterator $it)
{
$this->iterators[] = $it;
}
public function rewind()
{
foreach ($this->iterators as $it) {
$it->rewind();
}
$this->index = 0;
}
/**
* @return Array one or more current values
* @throws RuntimeException
*/
public function current()
{
$current = array();
foreach ($this->getCurrentIterators() as $key => $value) {
$current[$key] = $value->current();
}
return $current;
}
/**
* @return Iterator[]
*/
private function getCurrentIterators()
{
/* @var $compareFunction Callable */
$compareFunction = $this->compareFunction;
$iterators = $this->getValidIterators();
$r = uasort($iterators, $compareFunction);
if (FALSE === $r) {
throw new RuntimeException('Sorting failed.');
}
$compareAgainst = reset($iterators);
$sameIterators = array();
foreach ($iterators as $key => $iterator) {
$comparison = $compareFunction($iterator, $compareAgainst);
if (0 !== $comparison) {
break;
}
$sameIterators[$key] = $iterator;
}
ksort($sameIterators);
return $sameIterators;
}
/**
* @return Iterator[]
*/
private function getValidIterators()
{
$validIterators = array();
foreach ($this->iterators as $key => $iterator) {
$iterator->valid() && $validIterators[$key] = $iterator;
}
return $validIterators;
}
/**
* @return int zero based iteration count
*/
public function key()
{
return $this->index;
}
public function next()
{
foreach ($this->getCurrentIterators() as $iterator) {
$iterator->next();
}
$this->index++;
}
public function valid()
{
return (bool)count($this->getValidIterators());
}
}
/**
* Usage
*/
$it = new MergeCompareIterator($compareFunction, array($it1, $it2));
foreach ($it as $index => $values) {
printf("Iteration #%d:\n", $index);
foreach ($values as $iteratorIndex => $value) {
printf(" * [%d] => %s\n", $iteratorIndex, $value);
}
}
希望这会有所帮助。它仅适用于“内部”迭代器中的预排序数据,否则与当前元素比较的合并/追加策略没有意义。