我有一个MongoDB文档集合,如下所示:
[
{
"Continent":"Europe",
"Country":"France",
"City":"Paris"
},
{
"Continent":"Europe",
"Country":"France",
"City":"Marseille"
},
{
"Continent":"Europe",
"Country":"Germany",
"City":"Berlin"
},
{
"Continent":"Asia",
"Country":"China",
"City":"Beijing"
}
]
我想(在一个PHP脚本中但是有一个Mongo查询)最后得到一个像这样的关联数组:
$cities = array(
"Europe" => array(
"France" => array(
"Paris",
"Marseille",
),
"Germany" => array(
"Berlin",
),
),
"Asia" => array(
"China" => array(
"Beijing",
),
),
);
我只需要获得一个关联数组就能显示不同大陆的列表;国家和城市,但不是3个请求,因为我想允许用户过滤结果,所以如果在第一个输入中用户输入“欧洲”我必须在国家输入中仅显示“法国”和“德国”..
我没有问任何人正确的查询,但我想帮助找到正确的Mongodb函数,因为我对Mongo和NoSQL很新。
也许我可以使用“聚合”运算符和一些“组”,或链多个“不同”运算符......我真的不知道从哪里开始。
答案 0 :(得分:0)
尝试下一步方法:
function handleCities($json)
{
$result = [];
foreach(json_decode($json, true) as $city) {
$result[$city['Continent']][$city['Country']][] = $city['City'];
}
return $result;
}
$cities = '[
{
"Continent":"Europe",
"Country":"France",
"City":"Paris"
},
{
"Continent":"Europe",
"Country":"France",
"City":"Marseille"
},
{
"Continent":"Europe",
"Country":"Germany",
"City":"Berlin"
},
{
"Continent":"Asia",
"Country":"China",
"City":"Beijing"
}
]';
var_dump(handleCities($cities));