Cakephp 4 - 合并两个 ResultSet

问题描述

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

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

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

有什么建议吗?

在控制器中使用 ResultSet 的原因:我想将结果交付给模板/视图,并将其序列化并作为 JSON 交付。

谢谢 克里斯蒂安

解决方法

我不知道你的数据到底是什么样的,但为了完整起见,这里有一些有趣的集合 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
]

另见

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...