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"]}
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.