Home > Net >  Put 2 objects inside the object
Put 2 objects inside the object

Time:09-22

I'm writing some queries and receiving the $help_articles:

[
    {
        "id": 10,
        "title": "Creative Agency Creation",
        "sub_title": "Learn how to create creative agency and setup information and users",
        "featured_image": image.jpg",
        "content": "[{some content}]",
    },
    {
        "id": 12,
        "title": "Create New User",
        "sub_title": "Instruction to create new user",
        "featured_image": "56095569_step_3.jpg",
        "content": "[{some_content}]",
    }
]

Another query is returning $related_articles

[
    {
        "title": "Creative Agency Creation",
        "slug": "creative-agency-creation"
    },
    {
        "title": "Create New User",
        "slug": "create-new-user"
    },
]

I need 2 put this 2 objects in 1 like this:

{
"all_articles": [
    {
        "id": 10,
        "title": "Creative Agency Creation",
        "sub_title": "Learn how to create creative agency and setup information and users",
        "featured_image": image.jpg",
        "content": "[{some content}]",
    },
    {
        "id": 12,
        "title": "Create New User",
        "sub_title": "Instruction to create new user",
        "featured_image": "56095569_step_3.jpg",
        "content": "[{some_content}]",
    }
],
"related_articles": [
        {
            "title": "Creative Agency Creation",
            "slug": "creative-agency-creation"
        },
        {
            "title": "Create New User",
            "slug": "create-new-user"
        },
 ]
}

I'm making the following:

 $final = new \stdClass();
        $final=$help_articles;
        $final['related_articles'] = $related_articles;

            return response()->json($final);

But I didn't get the required result.

Please advice, what I'm doing wrong and how to fix this

CodePudding user response:

@Cbroe, thanks a lot, it's helped. The solution was simple:

 $final = [
            'all_articles' => $help_articles,
            'related_articles' => $related_articles
        ];
            return response()->json($final);

CodePudding user response:

What about compact()? It was like

$all_articles = []; //some array
$related_articles = []: //some data
return response()->json(compact(['all_articles', 'related_articles']));

CodePudding user response:

Try this it will work in your case.

$final = new stdClass();

$final->all_articles =  $all_articles;
$final->related_articles =  $related_articles;

return response()->json($final);
  • Related