0

Hi I need help [this is my table structure] and my current [JSON response is like this] and I want to convert this to [like this JSON response] Can anybody give some idea or any related code so that I can make my JSON response like that.

*Note I can't create another table to store user images

Bittu
  • 11
  • 2
  • Does this answer your question? [How to convert an array to object in PHP?](https://stackoverflow.com/questions/1869091/how-to-convert-an-array-to-object-in-php) – CBroe Jul 24 '20 at 13:12
  • I want optnl_img1, optnl_img2 ..... this key pair as an object. – Bittu Jul 24 '20 at 13:37
  • So? Push them into an array first then, and then convert that into an object. – CBroe Jul 24 '20 at 14:08
  • If you share any code like that would be so much helpful. – Bittu Jul 24 '20 at 14:18

1 Answers1

0

First you don't need to concatenate your base_url to all images, you can use it separately in your front file, unless it must be there.

Second you don't need to store user_id to your image structure, because you have id right in your table's structure.

anyway you can do something like snippet below.

I hope it works fine :)

Edit:

It is easier to work with arrays in PHP so I convert my code to array version and if you need to use object first convert your object to array and after snippet you can convert it to object like (object) $data

    foreach ($data as &$user) {
    if(!empty($user['main_image'])) {
        $user['main_image'] = $image_basepath . $user['main_image'];
    }

    $user['image'] = [];

    for($i = 1; $i <= 6; $i++) {
        $imgArr = [];
        $img = $user['optnl_img' . $i];
        unset($user['optnl_img' . $i]);

        if(isset($img) && !empty($img)) {
            $imgArr['id'] = $i;
            $imgArr['user_id'] = $user['id'];
            $imgArr['image'] = $image_basepath . $img;
        }

        $user['image'][] = $imgArr;
    }
}
MMDM
  • 465
  • 3
  • 11
  • Hello, You got exactly what I was looking for thank you very much but I am getting only the last image I need all the images like that. – Bittu Jul 24 '20 at 14:08