Yii2's mongodb collection - get all content of nested arrays

66
February 12, 2019, at 1:50 PM

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.

Answer 1

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

READ ALSO
Mysql subquery or something better

Mysql subquery or something better

I am somewhat new to mysql and I am having an issue on how I should best write the following querySay I have a table that has a datetime column as well as a few others I want to search on

66
How to insert data into two tabels?

How to insert data into two tabels?

I have two tables FILM(Id, Title, Director, Year, Category) and Record(Id, Film_id)

64
Connect to node.js after installing MySQL

Connect to node.js after installing MySQL

When I type var mysql=require('mysql');, I get an error that mysql module is not found

73