如何在PHP中更改数组结构

时间:2015-08-05 06:47:42

标签: php arrays object

我有一个以下形式的数组,

Array
(
    [0] => Array
        (
            [emailAddress] => abc@gmail.com
            [subject] => Hi
            [content] => How are you?
            [attachment] => QmFzZTY0IGlzIGFuIGVuY29kaW5nIHNjaGVtZSB1c2VkIHRvIHJlcHJlc2VudCBiaW5hcnkgZGF0YSBpbiBhbiBBU0NJSSBmb3JtYXQuIA==
            [fileName] => Base 64 Encoder
        )
)

我怎么能在下面的表格中找到它:

Array
(
    [emailAddress] => abc@gmail.com
    [subject] => Hi
    [content] => How are you?
    [attachments] => Array
        (
            [attachment] => QmFzZTY0IGlzIGFuIGVuY29kaW5nIHNjaGVtZSB1c2VkIHRvIHJlcHJlc2VudCBiaW5hcnkgZGF0YSBpbiBhbiBBU0NJSSBmb3JtYXQu
            [fileName] => Base 64 Encoder
        )

)

有没有办法将[attachments] => Array的类型转换为[attachments] => Object?如下所示:

Array
(
    [emailAddress] => abc@gmail.com
    [subject] => Hi
    [content] => How are you?
    [attachments] => Object
        (
            [attachment] => QmFzZTY0IGlzIGFuIGVuY29kaW5nIHNjaGVtZSB1c2VkIHRvIHJlcHJlc2VudCBiaW5hcnkgZGF0YSBpbiBhbiBBU0NJSSBmb3JtYXQu
            [fileName] => Base 64 Encoder
        )

)

我试图查看一些方法(比如array_push,array_splice等),但仍然无法获得它。希望有人可以帮助我。感谢。

1 个答案:

答案 0 :(得分:6)

试试这个

$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);