3

我有两个迭代器,我必须合并到一个结果中。

以下是数据样本:

ArrayIterator Object
(
[storage:ArrayIterator:private] => Array
    (
        [0] => Array
            (
                [period] => 04/04/2012 16:00:00
                [bl_subs] => 1
                [bl_unsubs] => 1
                [bl_block_total] => 1
            )

        [1] => Array
            (
                [period] => 04/04/2012 17:00:00
                [bl_subs] => 1
                [bl_unsubs] => 2
                [bl_block_total] => 0
            )

        [2] => Array
            (
                [period] => 04/04/2012 18:00:00
                [bl_subs] => 0
                [bl_unsubs] => 0
                [bl_block_total] => -1
            )

        [3] => Array
            (
                [period] => 04/04/2012 19:00:00
                [bl_subs] => 2
                [bl_unsubs] => 0
                [bl_block_total] => -2
            )

        [4] => Array
            (
                [period] => 04/04/2012 20:00:00
                [bl_subs] => 2
                [bl_unsubs] => 0
                [bl_block_total] => 1
            )

    )

)


ArrayIterator Object
(
[storage:ArrayIterator:private] => Array
    (
        [0] => Array
            (
                [period] => 04/04/2012 15:00:00
                [bl_avg] => 5
                [bl_full] => 0
            )

        [1] => Array
            (
                [period] => 04/04/2012 17:00:00
                [bl_avg] => 0
                [bl_full] => 7
            )

        [2] => Array
            (
                [period] => 04/04/2012 18:00:00
                [bl_avg] => 1
                [bl_full] => 0
            )

    )

)

我想通过键“句点”将它们合并到一个摘要迭代器中。

最终结果应如下所示:

ArrayIterator Object
(
[storage:ArrayIterator:private] => Array
    (
        [0] => Array
            (
                [period] => 04/04/2012 15:00:00
                [bl_subs] => 0
                [bl_unsubs] => 0
                [bl_avg] => 5
                [bl_full] => 0
                [bl_block_total] => 0
            )

        [1] => Array
            (
                [period] => 04/04/2012 16:00:00
                [bl_subs] => 1
                [bl_unsubs] => 1
                [bl_avg] => 0
                [bl_full] => 0
                [bl_block_total] => 1
            )

        [2] => Array
            (
                [period] => 04/04/2012 17:00:00
                [bl_subs] => 1
                [bl_unsubs] => 2
                [bl_avg] => 0
                [bl_full] => 7
                [bl_block_total] => 0
            )

        [3] => Array
            (
                [period] => 04/04/2012 18:00:00
                [bl_subs] => 0
                [bl_unsubs] => 0
                [bl_avg] => 1
                [bl_full] => 0
                [bl_block_total] => -1
            )

        [4] => Array
            (
                [period] => 04/04/2012 19:00:00
                [bl_subs] => 2
                [bl_unsubs] => 0
                [bl_avg] => 0
                [bl_full] => 0
                [bl_block_total] => -2
            )

        [5] => Array
            (
                [period] => 04/04/2012 20:00:00
                [bl_subs] => 2
                [bl_unsubs] => 0
                [bl_avg] => 0
                [bl_full] => 0
                [bl_block_total] => 1
            )

    )

)

如果我们不使用 foreach、for、while 或任何其他循环,那将是最好的。那是因为数据会很大,我们不希望出现内存问题。我正在尝试使用current()next()使用内部数组指针。

如果有人知道摆脱这种情况的方法,请告知。

4

3 回答 3

7

它两个迭代器总是排序的,你可以缓存它们,每次迭代比较哪个先出现(如果不相等)并处理那个。如果相等,则同等处理。

不相等:

$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 个或更多迭代器。因此,每次迭代都会根据迭代器的当前值相互比较迭代器。为此,使用了比较功能。您可以将其与usortDocs的工作方式进行比较:一个函数比较 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函数获取字符串进行比较。

因此,假设您有一个包含两个迭代器的数组,现在可以对其进行排序。也可以将第一个元素与下一个元素进行比较,以确定它们是否相等。

完成后,现在可以创建一个由多个迭代器组成的迭代器,并且在每次迭代时,附加的迭代器都会被排序,并且只有第一个迭代器(以及与其相等的迭代器)将作为当前迭代器返回并转发。像这样的流程:

DITAA 图表

由于排序已经通过比较函数完成,所以只需要封装这个迭代逻辑。由于排序适用于任何大小(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);
    }
}

希望这会有所帮助。它仅适用于“内部”迭代器中的预排序数据,否则与当前元素比较的合并/追加策略没有意义。

于 2012-04-05T08:36:55.047 回答
1

好的,这很简单。假设两个迭代器都已排序,您需要做的就是对它们进行合并排序(基本上):

function mergeIterators(Iterator $it1, Iterator $it2, $compare, $merge) {
    $result = array();
    //rewind both itertators
    $it1->rewind();
    $it2->rewind();
    while ($it1->valid() || $it2->valid()) {
        if (!$it1->valid()) {
            $cmp = 1;
        } elseif (!$it2->valid()) {
            $cmp = -1;
        } else {
            $cmp = $compare($it1->current(), $it2->current());
        }

        if ($cmp === 0) {
            // equal, merge together
            $result[] = $merge($it1->current(), $it2->current());
            $it1->next();
            $it2->next();
        } elseif ($cmp < 0) {
            //first is less than second
            $result[] = $it1->current();
            $it1->next();
        } else {
            $result[] = $it2->current();
            $it2->next();
        }
    }
    return $result;
}

这里唯一的技巧是传入正确的$compare函数和$merge函数......

这是一个快速示例:

$compare = function(array $val1, array $val2) {
    return strtotime($val1['period']) - strtotime($val2['period']);
};

$merge = function(array $val1, array $val2) {
    return array_merge($val1, $val2);
};

可能需要更改合并功能,因为它只是进行粗略合并,您可能想要做一些更复杂的事情(例如将键添加在一起等)...

但是这个函数足够通用,可以用于合并任何 2 个迭代器,而不仅仅是你的用例......

于 2012-04-05T12:02:41.787 回答
0

您可以使用AppendIteratorhttp://php.net/manual/en/class.appenditerator.php获取更多文档。

示例: http: //php.net/manual/en/function.iterator-to-array.php

$first = new ArrayIterator ( array (
        'k1' => 'a',
        'k2' => 'b',
        'k3' => 'c',
        'k4' => 'd' 
) );
$second = new ArrayIterator ( array (
        'k1' => 'X',
        'k2' => 'Y',
        'Z' 
) );

$combinedIterator = new AppendIterator ();
$combinedIterator->append ( $first );
$combinedIterator->append ( $second );

var_dump ( iterator_to_array ( $combinedIterator, false ) );

谢谢

:)

于 2012-04-05T08:20:03.830 回答