Skip to content
Advertisement

Format the json encode just like on laravel php

Supposed I have a query that gets the image from a certain tweet

[
     {
         "pic": "/upload/15680712995mb.jpg",
        "tweet_id": "48"
     },
     {
         "pic": "/upload/1568071299test.PNG",
         "tweet_id": "48"
     },
     {
         "pic": "/upload/1568015310test.PNG",
         "tweet_id": "47"
     } 
]

And I have a result also from a query that gets all of the tweet

[
    {
        "id": "48",
        "tweet": "test",
    },
    {
        "id": "47",
        "tweet": "test tweet",
    },

    {
        "id": "45",
        "tweet": "test tweet 3",
    }
]

How can I format the result like this (Just like on laravel)

[
    {
        "id": "48",
        "tweet": "test",
        "pics": [
            [
                "/upload/15680712995mb.jpg"
            ],
            [
               "/upload/1568071299test.PNG"
            ],
        ]
    },
    {
        "id": "47",
        "tweet": "test tweet",
        "pics" : [
            [
                 "/upload/1568015310test.PNG"
            ]
        ]
    },
    {
        "id": "45",
        "tweet": "test tweet 3",
        "pics" : []
    }
]

And this is my simplified code

public function getTweets()
{
    $pics =  $this->model->getPics();

    $aTweets =  $this->model->getTweets();
    $map = [];
    $props = [];
    foreach ($aTweets as $sTweet) {
        $map['id'] =  $sTweet['id'];
        $map['tweet'] =  $sTweet['tweet'];

        foreach ($pics as $pic) {
            if ($pic['id'] === $sTweet['tweet_id']) {
                $map['pics'] = [$pic['pic']];
            }
        }

        $props[] = $map;

    }
    return $props;
}

but it just gives me the following output

{
    "id": "48",
    "tweet": "test",
    "pics": [
        "/upload/1568015310test.PNG"
    ]
},
{
    "id": "47",
    "tweet": "test tweet",
    "pics": [
        "/upload/1568015310test.PNG"
    ]
},

Any idea how can I format the result. thanks in advance.?

Advertisement

Answer

I’m not sure what’s troubling you but in order to add multiple values inside, just put another nesting like what I’ve eluded in the comments section:

$map['pics'][] = $pic['pic'];
        //   ^

So to complete the answer:

$map = [];
$props = [];
foreach ($aTweets as $sTweet) {
    $map['id'] =  $sTweet['id'];
    $map['tweet'] =  $sTweet['tweet'];
    $map['pics'] = []; // initialize
    foreach ($pics as $pic) {
        if ($pic['tweet_id'] === $sTweet['id']) {
            $map['pics'][] = [$pic['pic']];
        }
    }

    $props[] = $map;
}

This essentially creates another dimension for pics index as an array and continually pushing, provided they have the same ID.

Sidenote: tweet_id is to pics and id is to aTweets. Your’s have the other way around.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement