简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM