我在我的应用程序中使用Mongo DB和Slim PHP。
在mongo我有这个对象数组
"dashboards" : [
{
"_id" : ObjectId("52b96365481b9c02091d8698"),
"title" : "Default title",
"subtitle" : "Default subtitle",
"metric_views" : [ ]
},
{
"_id" : ObjectId("52b9665f481b9c06091d8698"),
"title" : "asdasdasd",
"subtitle" : "asdasdasdas",
"metric_views" : [ ]
},
{
"_id" : ObjectId("52b96666481b9c04091d8697"),
"title" : "asdasdas",
"subtitle" : "dasdasdas",
"metric_views" : [ ]
}
]
对于删除我写了这个函数
function removeDashboard ($user,$dashboardMongoId) {
foreach ($user['dashboards'] as $key => $dashboard) {
if($user['dashboards'][$key]['_id']==$dashboardMongoId) {
unset($user['dashboards'][$key]);
break;
}
}
return $user['dashboards'];
}
删除一个对象后,我的仪表板看起来像这样
"dashboards" : {
"1" : {
"_id" : ObjectId("52b9665f481b9c06091d8698"),
"title" : "asdasdasd",
"subtitle" : "asdasdasdas",
"metric_views" : [ ]
},
"2" : {
"_id" : ObjectId("52b96666481b9c04091d8697"),
"title" : "asdasdas",
"subtitle" : "dasdasdas",
"metric_views" : [ ]
}
}
[]成为{},我得到对象“1”,“2”的数字,但整个应用程序都是这样的。有谁知道为什么会发生这种情况,我应该解决它还是可以保持这种状态?
谢谢!
更新:
如果Array中没有仪表板,我可以创建默认仪表板,这可能就是问题所在,这里是代码
$app->get('/getDashboards', function () {
// Connect to database and select collection for loged in user
$collection = selectMongoCollection('ctstats', 'users');
$user = findLoggedUser($collection);
// Get all dashboards for user
$data = $user['dashboards'];
if(sizeof($user['dashboards']) == 0) {
// Creating default dashboard
$dashboard = array(
"_id" => new MongoId(),
"title" =>"Default title",
"subtitle" =>"Default subtitle",
"metric_views" => array()
);
// Saving dashboard to collection
array_push($user['dashboards'],$dashboard);
// Updating mongo with new data
$collection->update($user,$user['dashboards']);
$collection->save($user);
}
echo json_encode($user['dashboards']);
});
答案 0 :(得分:0)
为什么不使用MongoDB客户端的 MongoCollection :: remove PHP函数。 它将从给定条件的集合中删除内容。
答案 1 :(得分:0)
这是在你的php函数中发生的:
function removeDashboard ($user,$dashboardMongoId) {
foreach ($user['dashboards'] as $key => $dashboard) {
if($user['dashboards'][$key]['_id']==$dashboardMongoId) {
unset($user['dashboards'][$key]);
break;
}
}
return $user['dashboards'];
}
在php中,每种数组都是一个数组(在php意义上)。对于mongodb / javascript一般情况并非如此,其中数组特别是基于0的数字索引数组,而不是作为键值数组的散列/文档/对象。当通过mongodb驱动程序传递数据数组时,必须进行转换,并且我认为它基本上检查是否存在零索引以确定最适合的mongodb存储类型。
在您的PHP代码中,您删除与索引0对应的值,而让所有其他键保持不变。由于您似乎并不关心密钥,因此可以使用 array_value()轻松解决此问题,这会将数组密钥神奇地重建为基于0的纯数字索引列表:
function removeDashboard ($user,$dashboardMongoId) {
foreach ($user['dashboards'] as $key => $dashboard) {
if($user['dashboards'][$key]['_id']==$dashboardMongoId) {
unset($user['dashboards'][$key]);
break;
}
}
return array_values($user['dashboards']);
}