MizaUnic
MizaUnic

Reputation: 79

How to Change Array Structure in PHP

I have an array in the following form,

Array
(
    [0] => Array
        (
            [emailAddress] => [email protected]
            [subject] => Hi
            [content] => How are you?
            [attachment] => QmFzZTY0IGlzIGFuIGVuY29kaW5nIHNjaGVtZSB1c2VkIHRvIHJlcHJlc2VudCBiaW5hcnkgZGF0YSBpbiBhbiBBU0NJSSBmb3JtYXQuIA==
            [fileName] => Base 64 Encoder
        )
)

How could I have it on the following form:

Array
(
    [emailAddress] => [email protected]
    [subject] => Hi
    [content] => How are you?
    [attachments] => Array
        (
            [attachment] => QmFzZTY0IGlzIGFuIGVuY29kaW5nIHNjaGVtZSB1c2VkIHRvIHJlcHJlc2VudCBiaW5hcnkgZGF0YSBpbiBhbiBBU0NJSSBmb3JtYXQu
            [fileName] => Base 64 Encoder
        )

)

And is there any way to convert the type of [attachments] => Array to [attachments] => Object? like below:

Array
(
    [emailAddress] => [email protected]
    [subject] => Hi
    [content] => How are you?
    [attachments] => Object
        (
            [attachment] => QmFzZTY0IGlzIGFuIGVuY29kaW5nIHNjaGVtZSB1c2VkIHRvIHJlcHJlc2VudCBiaW5hcnkgZGF0YSBpbiBhbiBBU0NJSSBmb3JtYXQu
            [fileName] => Base 64 Encoder
        )

)

I've tried to look number of methods (like array_push, array_splice and etc.) but still can't get it. Hope someone can help me with that. Thanks.

Upvotes: 3

Views: 375

Answers (1)

Narendrasingh Sisodia
Narendrasingh Sisodia

Reputation: 21422

Try this

$result = array();
$result = $arr[0];
$result['attachments'] = new stdClass();
$result['attachments']->attachment = $result['attachment'];
$result['attachments']->fileName = $result['fileName'];
unset($result['attachment']);
print_r($result);

Upvotes: 6

Related Questions