0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

MongoId型データをjson_encodeで変換する際の注意

Posted at
mongoid_print.php
<?php
echo (new MongoId());
結果

"5170b4f67b2a7d0c1f000000 "
通常、echo(print)する際は自動的に__toString()が実行されるので、
IDの16進表現で表示される。

だが、

mongoid_json_encode.php
<?php
echo json_encode(new MongoId());
結果

{"$id":"5170b4f67b2a7d0c1f000000"}
json_encodeにそのままMongoIdオブジェクトを渡すと上記のような配列を
文字列化してしまうようである。

mongoid_json_encode.php
<?php
$mongoId = new \MongoId();
echo json_encode($mongoId->__toString());
結果

"5170b76d7b2a7de818000000"
明示的に__toString()すれば回避できる。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?