Deekshith's avatar

Merge different get query results with pagination in array format

i am using corcel package to get wordpress posts and i am getting all the posts which matches some categories like below,

$categories = ['current-affairs-2','current-events-2','editorials'];

$related = new Collection([]);
            // return $pagedetail->assignedcategories->first();
    
            foreach($categories  as $cat)
            {
            
                $categorydetail = Taxonomy::slug($cat->category)->first();
                
                $catposts =  $categorydetail->posts()
                                    ->where('post_status', 'publish')
                                    ->whereYear('post_date',$year)
                                    ->whereMonth('post_date', $month)
                                    ->newest()
                                    ->select('ID','post_title','post_date','post_date_gmt','post_status','comment_status','post_name','post_modified','post_modified_gmt','guid','post_type')
                                    ->get();
    
                $related = $related->merge($catposts);
            }
    
            $unique = $related->unique('ID');
            
            return $final = $unique->sortByDesc('post_date')->paginate(20);

Above code returning like below format,

{
    "current_page": 1,
    "data": {
        "36": {

				},
			"37" :{

			}
}
}

but i want response in below format,

{
    "current_page": 1,
    "data": [
         {

				},
			{

			}
]
}

like this i should get array structure for data key but if i use merge of collection then i am not getting array structure. if use only one record without forleach then i will get array structure.

any help?

0 likes
4 replies
Deekshith's avatar

@jlrdw thanks for the reply. solved this by adding values() like below,

 $final = $unique->sortByDesc('post_date')->values()->paginate(15);
Deekshith's avatar

@jlrdw my answer is working only for page 1 and for page 2 again number identifier is showing like below,

{
    "current_page": 1,
    "data": {
        "36": {

				},
			"37" :{

			}
}
}

Can you please help to get the data in below format for data key?

{
    "current_page": 1,
    "data": [
         {

				},
			{

			}
]
}

i have used values() before but it is working only for first page but if use ?page=2 then it is showing in first format.


$final = $unique->sortByDesc('post_date')->values()->paginate(15);

Please or to participate in this conversation.