如何在 PHP 中将数组转换为对象?

2022-01-31 00:00:00 arrays object casting php

如何将这样的数组转换为对象?

How can I convert an array like this to an object?

[128] => Array
    (
        [status] => "Figure A.
 Facebook's horizontal scrollbars showing up on a 1024x768 screen resolution."
    )

[129] => Array
    (
        [status] => "The other day at work, I had some spare time"
    )

推荐答案

在最简单的情况下,将数组强制转换"为对象可能就足够了:

In the simplest case, it's probably sufficient to "cast" the array as an object:

$object = (object) $array;

另一种选择是将标准类实例化为变量,并在重新分配值时循环遍历数组:

Another option would be to instantiate a standard class as a variable, and loop through your array while re-assigning the values:

$object = new stdClass();
foreach ($array as $key => $value)
{
    $object->$key = $value;
}

正如 Edson Medina 所指出的,一个真正干净的解决方案是使用内置的 json_函数:

As Edson Medina pointed out, a really clean solution is to use the built-in json_ functions:

$object = json_decode(json_encode($array), FALSE);

这也(递归地)将您的所有子数组转换为您可能想要也可能不想要的对象.不幸的是,它比循环方法有 2-3 倍的性能损失.

This also (recursively) converts all of your sub arrays into objects, which you may or may not want. Unfortunately it has a 2-3x performance hit over the looping approach.

警告!(感谢 Ultra 的评论):

Warning! (thanks to Ultra for the comment):

json_decode 在不同的环境下以不同的方式转换 UTF-8 数据.我最终在本地获得了240.00"的价值,在生产上获得了240"的价值——巨大的灾难.Morover 如果转换失败,则字符串获取返回为 NULL

json_decode on different enviroments converts UTF-8 data in different ways. I end up getting on of values '240.00' locally and '240' on production - massive dissaster. Morover if conversion fails string get's returned as NULL

相关文章