CERCUA
CERCUA

Reputation: 13

Laravel build an array from query results

here are some objects which i fetch from query results

{
    {
        "name": "John",
        "notification": "sms"
    },
    {
        "name": "John",
        "notification": "email"
    },
}

From those results, i want to build an array like this

{
   "name":"John",
   "notification":['email', 'sms']
}

Anyone who can light up my day?

Upvotes: 0

Views: 62

Answers (1)

fusion3k
fusion3k

Reputation: 11689

Assuming your original object is an array of objects, if you want a single object as result, you can do this ($data is your original array):

$result = (object) [ 'name' => $data[0]->name, 'notifications' => [] ];
foreach( $data as $item ) $result->notifications[] = $item->notification;

On php 7, you can also do this:

$result = (object) [ 'name' => $data[0]->name, 'notifications' => array_column( $data, 'notification' ) ];

Both examples have this result:

stdClass Object
(
    [name] => John
    [notifications] => Array
        (
            [0] => sms
            [1] => email
        )

)

Or, wiht JSON syntax:

{"name":"John","notifications":["sms","email"]}

eval.in demo

Upvotes: 1

Related Questions