首页 > 解决方案 > Cakephp 4 - 合并两个结果集

问题描述

作为 query->find() 的结果,我得到了两个 ResultSet。

现在我想以特定的顺序合并两者,例如遍历 ResultSet1 并且在每 10 个项目之后我想合并 ResultSet2 中的一个项目。

我找到了 appendItem 函数,但是它似乎没有在正确的位置对我的项目进行排序。

有什么建议么?

留在控制器中的 ResultSet 的原因:我想将结果传递到模板/视图,并将其序列化并作为 JSON 传递。

谢谢克里斯蒂安

标签: cakephpcollectionsquery-buildercakephp-4.x

解决方案


我不知道你的数据到底是什么样的,但为了完整起见,这里有一些有趣的集合 foo:

$itemsA = collection([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]);
$itemsB = collection(['a', 'b', 'c', 'd', 'e', 'f', 'g']);

使用自定义展开在块之后产生元素:

$collection = $itemsA
    ->chunk(2)
    ->unfold(function (array $chunks, int $key) use ($itemsB) {
        // yield every itemA element in the chunk
        yield from $chunks;

        // only yield itemB element in case there's 2 preceding itemA elements
        if (count($chunks) === 2) {
            static $index = 0;

            // yield itemB element in case one exists at the (next) index
            $itemB = $itemsB->take(1, $index ++)->first();
            if ($itemB) {
                yield $itemB;
            }
        }
    });

使用映射将元素附加到块:

$collection = $itemsA
    ->chunk(2)
    ->map(function (array $chunk) use ($itemsB) {
        // only add itemB element in case there's 2 preceding itemA elements
        if (count($chunk) === 2) {
            static $index = 0;

            // add itemB element in case one exists at the (next) index
            $itemB = $itemsB->take(1, $index ++)->first();
            if ($itemB) {
                $chunk[] = $itemB;
            }
        }

        return $chunk;
    })
    ->unfold();

对于这两个示例,$collection->toArray()将返回:

[
  (int) 0 => (int) 1,
  (int) 1 => (int) 2,
  (int) 2 => 'a',
  (int) 3 => (int) 3,
  (int) 4 => (int) 4,
  (int) 5 => 'b',
  (int) 6 => (int) 5,
  (int) 7 => (int) 6,
  (int) 8 => 'c',
  (int) 9 => (int) 7,
  (int) 10 => (int) 8,
  (int) 11 => 'd',
  (int) 12 => (int) 9,
  (int) 13 => (int) 10,
  (int) 14 => 'e',
  (int) 15 => (int) 11
]

也可以看看


推荐阅读