dousu8767
2019-02-11 14:05
浏览 315

Yii2的mongodb集合 - 获取嵌套数组的所有内容

I have a Yii2 mongodb's collection that looks like this:

{
 "_id" : "123",
 "books" : [
  {
   "author" : "John",
   "title" : "The Book"
  },
  {
   "author" : "Smith",
   "title" : "Something!"
  }
 ]
}
{
 "_id" : "321",
 "books" : [
  {
   "author" : "John",
   "title" : "The Book"
  }
 ]
}
...

And I want to get an array of all books (an array of arrays basically):

[
  {
   "author" : "John",
   "title" : "The Book"
  },
  {
   "author" : "Smith",
   "title" : "Something!"
  },
  {
   "author" : "John",
   "title" : "The Book"
  }
...
]

I saw answers to close questions, but they all achieve something a bit different. Also tried $collection->distinct('books', [], []) and it worked, but it removed duplicates which is unacceptable.

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dongyi2083 2019-02-12 13:32
    已采纳

    Use this MongoDB query to get this resultset

    db.collection.aggregate([
        { $unwind : "$books"}, 
        { $group: { 
          _id: null, 
          items: 
            { $push: "$books" } 
        }}
    ]);
    
    已采纳该答案
    打赏 评论
  • dongzhang6677 2019-02-11 16:27

    Let's try like this way using foreach()?

    <?php
    $json = '[{"_id":"123","books":[{"author":"John","title":"The Book"},{"author":"Smith","title":"Something!"}]},{"_id":"321","books":[{"author":"John","title":"The Book"}]}]';
    
    $array = json_decode($json, 1);
    $ids = [];
    foreach($array as $v) {
        foreach($v['books'] as $book){
            $books[] = $book;
        }
    }
    echo json_encode($books);
    ?>
    

    Output:

    [{"author":"John","title":"The Book"},{"author":"Smith","title":"Something!"},{"author":"John","title":"The Book"}]
    

    DEMO: https://3v4l.org/hdJ8H

    打赏 评论

相关推荐 更多相似问题