dousu8767 2019-02-11 14:05
浏览 323
已采纳

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

    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 编译arm板子的gcc
  • ¥20 C语言用栈实现无向图邻接矩阵广度优先遍历
  • ¥15 C++代码报错问题,c++20协程
  • ¥15 c++图Djikstra算法求最短路径
  • ¥15 Linux操作系统中的,管道通信问题
  • ¥15 ansible tower 卡住
  • ¥15 等间距平面螺旋天线方程式
  • ¥15 通过链接访问,显示514或不是私密连接
  • ¥100 系统自动弹窗,键盘一接上就会
  • ¥50 股票交易系统设计(sql语言)