1

Tried merging two JSON responses into a single one but the problem is the data is displayed in two arrays and I want it in a single array. How do I achieve it in Lumen/Laravel

Tried contatinating two arrays or responses

 public function index(Request $request)
    {
        $post = Post::orderBy('id', 'DESC')->get();
        $post_images = PostImage::orderBy('id', 'DESC')->get();
        return $this->successResponse($posts.$post_image );        
    }

Expected:-

{
    "post": {
        "id": 14,
        "post_id": 798965728,
        "user_id": 1,
        "location": "first",
        "title": "un8852",
        "cooked_time": "1554329910",
        "dispose_time": "1554373110",
        "food_type": "nv",
        "description": "asdfg",
        "serve_quantity": 23,
        "lat": 19.08,
        "lon": 73,    
        "id": 10,
        "post_id": 798965728,
        "image_name1": null,
        "image_name2": null,
        "image_name3": null,
        "image_name4": null,
        "image_name5": null,
    },
    "st": "1",
    "msg": "success"
}

Got:-

{
   "post":"{\"id\":14,\"post_id\":798965728,\"user_id\":1,\"location\":\"first\",\"title\":\"un8852\",\"cooked_time\":\"1554329910\",\"dispose_time\":\"1554373110\",\"food_type\":\"nv\",\"description\":\"asdfg\",\"serve_quantity\":23,\"lat\":19.08,\"lon\":73,\"created_at\":\"2019-04-04 10:20:18\",\"updated_at\":\"2019-04-04 10:20:18\"}{\"id\":10,\"post_id\":798965728,\"image_name1\":null,\"image_name2\":null,\"image_name3\":null,\"image_name4\":null,\"image_name5\":null,\"created_at\":\"2019-04-04 10:20:18\",\"updated_at\":\"2019-04-04 10:20:18\"}",
   "st":"1",
   "msg":"success"
}
4
  • 1
    May help if you include the source data, we have expected results, actual results, but not that [source data] - which is well ... kind of important. Commented Apr 8, 2019 at 20:28
  • I can tell you, You'll prolly want to use array_replace_recursive($primary, $secondary) after json_decoding them both. PS prolly is not a word, but I like it. Ok .. turns out it is oxforddictionaries :-( Commented Apr 8, 2019 at 20:31
  • @ArtisticPhoenix can you help me with this kind of problem stackoverflow.com/questions/55593703/… Commented Apr 11, 2019 at 5:09
  • Unfortunately I have yet to use Laravel, I'm actually in the planing stage of getting a project done for my work using it, but we are going it initial outsource it as I am too busy with other things. But I plan to build on it later, basically it's a CRUD system for our incoming data, which should be fairly easy to do. Then later I plant to build onto it. Currently we use mainly Code Igniter 2, which I built about 5 years ago and continue to improve. Commented Apr 11, 2019 at 5:16

3 Answers 3

2

There are some missing pieces there, but I think I see what's happening.

Based on the result you're getting, it looks like $posts and $post_image in this code are eloquent models.

return $this->successResponse($posts.$post_image ); 

When you concatenate them, their __toString() methods convert them to strings, which is done using the toJson() method. So basically you have two JSON objects stuck together, which isn't valid JSON, and then the successResponse() method encodes them again.

To merge them, you can convert them to arrays, merge those, then pass the result to successResponse().

$merged = array_merge($posts->toArray(), $post_image->toArray());
return $this->successResponse($merged);

The result you want is impossible, though. The "post" object has two different values of "id". You'll only be able to get one. If you use

$merged = array_merge($posts->toArray(), $post_image->toArray());

Then the id value of the second object will replace the first one. If you want to keep the first id value, you need to use union instead of array_merge.

$merged = $a->toArray() + $b->toArray(); 
Sign up to request clarification or add additional context in comments.

1 Comment

0

You can definitely concatenate two JSON arrays, You have to parse the objects and concatenate them and re stringify.

This question might be answered here also. https://stackoverflow.com/a/10384890/1684254

1 Comment

0

I think you can't concatenate 2 JSON objects as strings.

The proper way would be to:

  1. Get the Post and the PostImage objects

    $post = Post::orderBy('id', 'DESC')->get();

    $post_images = PostImage::orderBy('id', 'DESC')->get();

  2. Serialize the Post object https://laravel.com/docs/5.8/eloquent-serialization

  3. Use the method described below to add each field of the PostImage object (image_name1 .. image_name5) to the JSON How to add attribute in JSON in PHP?

  4. Return the JSON

Update:

Post::orderBy('id','DESC')->get()-> first() returns one object.

Post::orderBy('id','DESC')->get() returns a collection of objects and it would require a different approach.

Try this:

$post = Post::orderBy('id', 'DESC')->get();

$post->map(function ($item, $key) {
    $post_images = PostImage::where('post_id', $item->id)->get()->first();
    $item->setAttribute('image_name1',$post_images->image_name1);
    $item->setAttribute('image_name2',$post_images->image_name2);
    $item->setAttribute('image_name3',$post_images->image_name3);
    $item->setAttribute('image_name4',$post_images->image_name4);
    $item->setAttribute('image_name5',$post_images->image_name5);
    return $item;
});

return $this->successResponse($posts);

3 Comments

but it works fine if I try for $post = Post::orderBy('id','DESC')->get()-> first() values but not for all when i remove first() function. It specifies that image_name1 doesnt exist in collection
I updated the answer. If that doesn't work for you please explain in more details what you want to do.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.