Php 获取MongoDB中多个嵌入文档的平均数量
我正在使用highcharts制作一个向下展开的图表。这将显示多个具有平均值的项目,并将在具有每个值的列中向下展开。问题是,我无法得到每个项目的平均数量。。 来自mongo的JSON如下所示:Php 获取MongoDB中多个嵌入文档的平均数量,php,json,mongodb,highcharts,Php,Json,Mongodb,Highcharts,我正在使用highcharts制作一个向下展开的图表。这将显示多个具有平均值的项目,并将在具有每个值的列中向下展开。问题是,我无法得到每个项目的平均数量。。 来自mongo的JSON如下所示: { "_id" : ObjectId("57f4dd6c45db428df9a5541b"), "id" : 68, "project_code" : 13110202, "samples" : [ {
{
"_id" : ObjectId("57f4dd6c45db428df9a5541b"),
"id" : 68,
"project_code" : 13110202,
"samples" : [
{
"sample_name" : "1678_2",
"perc" : "75.97"
},
{
"sample_name" : "2012_1B-5",
"perc" : "75.33",
},
{
"sample_name" : "2012_1B-8",
"perc" : "77.28",
}]
}, {
"_id" : ObjectId("57f4dd6c45db428df9a5541a"),
"id" : 70,
"project_code" : 1235125,
"samples" : [
{
"sample_name" : "Ben",
"perc" : "30.97"
},
{
"sample_name" : "Anna",
"perc" : "81.25",
},
{
"sample_name" : "Sarah",
"perc" : "80.23",
}]
},
我试图浏览文档,通过嵌入的文档示例,获取所有perc_映射值,计算平均值,并将其放入用于HighChart的JSON中。我现在拥有的代码:
foreach ($id_array as $char) {
$cursor = $collection->find(array("_id" => new MongoId($char)));
foreach ($cursor as $document) {
if (is_array($document['samples'])) {
foreach ($document['samples'] as $samples) {
array_push($perc_total, $samples['perc']);
$average_of_foo = array_sum($perc_total) / count($perc_total);
}
}
}
}
var_dump($average_of_foo);
foreach ($id_array as $char) {
$cursor = $collection->find(array("_id" => new MongoId($char)));
foreach ($cursor as $document) {
if (is_array($document['samples'])) {
foreach ($document['samples'] as $samples) {
$array =
array("name" => $document['project_code'],
// Here is will add the average
"y" => (float) $samples['perc'],
"drilldown" => $char
);
array_push($array_data, $array);
}
}
}
}
能否请您的问题包含所需的JSON输出?此外,您可能需要更改模式设计,即将
perc_映射的
值转换为数字值,而不是当前的字符串。那么,您当前代码的哪一部分不工作?我已经让它工作了!我将很快用解决方案更新我的问题。