MENU

PHP Json数据 转为BSON格式插入Mongo数据库

May 11, 2019 • 已被 422 位童鞋围观过 • 代码分享

JSON格式理论上是不能直接插入Mongo的 使用json_decode()函数后 转换为数组 如果不是多维数组,可以直接插入,但是如果是多维数组的话 类似下面的数组就不能直接插入,如果插入后 多维数组丢失。

{ "id" : "5599", "name" : "奶娃后妈粉嫩嫩", "author" : "小熊哭了", "tags" : [ { "id" : "4764", "name" : "豪门", "parentid" : "65" }, { "id" : "4812", "name" : "破镜重圆", "parentid" : "65" } ], "status" : "2" }

json_decode()转换后插入 就变成了

{ "id" : "5599", "name" : "奶娃后妈粉嫩嫩", "author" : "小熊哭了", "tags" : "Array", "status" : "2" }

解决办法

$json='{ "id" : "5599", "name" : "奶娃后妈粉嫩嫩", "author" : "小熊哭了", "tags" : [ { "id" : "4764", "name" : "豪门", "parentid" : "65" }, { "id" : "4812", "name" : "破镜重圆", "parentid" : "65" } ], "status" : "2" }';
$bson = MongoDB\BSON\fromJSON($json);
$value = MongoDB\BSON\toPHP($bson);

运行环境 PHP7.3 MongoDB

Last Modified: September 28, 2023