0

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?

2
  • The source is an array of objects? The name is unique or you can have different names in same array? Commented Apr 19, 2016 at 12:18
  • @fusion3k ("name","notification") is unique Commented Apr 19, 2016 at 12:34

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you @fusion3k, this answer is very helpful for me, you save my day

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.