Group/change query array output

So i’m working on an query, this one will get all results(in this case translation values) en outputs an array. This query will output all found results but I need the arrays to be grouped by id so that it’s easy to loop them per id to make sure all translations are grouped.

I want to group them with the cms_blog_id.

Used query:


     $query = new Query;


        $blogSlugs = $query->select('language, translation')

            ->from(['cbt'=>'cms_blog_translation'])

            ->leftJoin(['cb'=>'cms_blog'], 'cb.id=cbt.cms_blog_id')

            ->where(['cb.is_deleted' => 0,

                     'cb.is_enabled' => 1,

                     //'cbt.language'

                     'cbt.attribute' => 'slug'])

            ->all();


        return $blogSlugs;//

// current output


Array

(

   [0] => Array

        (

            [language] => de

            [translation] => 

        )


    [1] => Array

        (

            [language] => en

            [translation] => 

        )


    [2] => Array

        (

            [language] => es

            [translation] => 

        )


     // many more


]

looking for something like:


[

    '123' => [

        ['id' => '123', 'data' => 'abc', 'device' => 'laptop']

    ],

    '345' => [ // all elements with this index are present in the result array

        ['id' => '345', 'data' => 'def', 'device' => 'tablet'],

        ['id' => '345', 'data' => 'hgi', 'device' => 'smartphone'],

    ]

]

Hi,

… okay, now we know how your output currectly looks like, but how SHOULD it look like?

that is not really clear to me?

EDIT:

Sorry, I just realized you wanted to group them after "cms_blog_id".

Yii has a lot of nice helpers to re-index / map arrays. ;)

Take a look here:

http://www.yiiframework.com/doc-2.0/guide-helper-array.html

Best Regards

Okay so not doing anything with the query but with the array…nice.

Arrayhelp::index() does the trick.

Thanks!

Hello again,

If you want to, you can also do it directly inside the query:

http://www.yiiframework.com/doc-2.0/yii-db-activequeryinterface.html

And look for "indexBy"

… something like this:




$query->select('language, translation')

	->from(['cbt'=>'cms_blog_translation'])

	->leftJoin(['cb'=>'cms_blog'], 'cb.id=cbt.cms_blog_id')

	->where(['cb.is_deleted' => 0,

			 'cb.is_enabled' => 1,

			 //'cbt.language'

			 'cbt.attribute' => 'slug'])

	->indexBy('cbt.cms_blog_id')

	->all();



(not tested at all)

Best Regards

Thanks but this isnt working.