How to convert an array to object in PHP?(如何在 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
这篇关于如何在 PHP 中将数组转换为对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 PHP 中将数组转换为对象?
基础教程推荐
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
- 如何在 Laravel 中使用 React Router? 2022-01-01
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
- 如何替换eregi() 2022-01-01
- PHP 类:全局变量作为类中的属性 2021-01-01
