我需要了解一个MongoCollection-> group()特性。对于组()PHP手册陈述了如下:在PHP中用reduce()多重推动MongoCollection-> group()
<?php
$collection->insert(array("category" => "fruit", "name" => "apple"));
$collection->insert(array("category" => "fruit", "name" => "peach"));
$collection->insert(array("category" => "fruit", "name" => "banana"));
$collection->insert(array("category" => "veggie", "name" => "corn"));
$collection->insert(array("category" => "veggie", "name" => "broccoli"));
$keys = array("category" => 1);
$initial = array("items" => array());
$reduce = "function (obj, prev) { prev.items.push(obj.name); }";
$g = $collection->group($keys, $initial, $reduce);
echo json_encode($g['retval']);
?>
有类似结果数组:
[{"category":"fruit","items":["apple","peach","banana"]},{"category":"veggie","items":["corn","broccoli"]}]
现在,我看到MongoCode减少()函数把该项目的名称进入结果数组。但是如果我想再推一个字段,即水果的颜色?
基本上,我需要的是有一个这样的输出:
[{"category":"fruit","items":[["apple", "red"],["peach", "peach"],["banana", "yellow"]]},{"category":"veggie","items":[["corn", "yellow"],["broccoli", "green"]]}]
,所以我想我应该推()以某种方式不同......究竟怎么了?我无法在任何地方找到正确的语法。提前
感谢和我的英文不好:-)
弗朗西斯
谢谢@rajesh。我解决了它并发布了一个解决方案。 – godzillante