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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1869091/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 04:07:12  来源:igfitidea点击:

How to convert an array to object in PHP?

phparraysobjectcasting

提问by streetparade

How can i convert an array like this to 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
    )

采纳答案by streetparade

This one worked for me

这个对我有用

  function array_to_obj($array, &$obj)
  {
    foreach ($array as $key => $value)
    {
      if (is_array($value))
      {
      $obj->$key = new stdClass();
      array_to_obj($value, $obj->$key);
      }
      else
      {
        $obj->$key = $value;
      }
    }
  return $obj;
  }

function arrayToObject($array)
{
 $object= new stdClass();
 return array_to_obj($array,$object);
}

usage :

用法 :

$myobject = arrayToObject($array);
print_r($myobject);

returns :

返回:

    [127] => stdClass Object
        (
            [status] => Have you ever created a really great looking website design
        )

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

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

like usual you can loop it like:

像往常一样,你可以像这样循环它:

foreach($myobject as $obj)
{
  echo $obj->status;
}

回答by jlb

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;
}

As Edson Medinapointed out, a really clean solution is to use the built-in json_functions:

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

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

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 hitover the looping approach.

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

Warning!(thanks to Ultra for the comment):

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

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

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

回答by Shahbaz

you can simply use type casting to convert an array to object.

您可以简单地使用类型转换将数组转换为对象。

// *convert array to object* Array([id]=> 321313[username]=>shahbaz)
$object = (object) $array_name;

//now it is converted to object and you can access it.
echo $object->username;

回答by johannes

The easy way would be

简单的方法是

$object = (object)$array;

But that's not what you want. If you want objects you want to achieve something, but that's missing in this question. Using objects just for the reason of using objects makes no sense.

但这不是你想要的。如果你想要对象,你想要实现一些东西,但在这个问题中却没有。仅仅为了使用对象而使用对象是没有意义的。

回答by Edson Medina

Quick hack:

快速破解:

// assuming $var is a multidimensional array
$obj = json_decode (json_encode ($var), FALSE);

Not pretty, but works.

不漂亮,但有效。

回答by Julius F

Here are three ways:

以下是三种方式:

  1. Fake a real object:

    class convert
    {
        public $varible;
    
        public function __construct($array)
        {
            $this = $array;
        }
    
        public static function toObject($array)
        {
            $array = new convert($array);
            return $array;
        }
    }
    
  2. Convert the array into an object by casting it to an object:

    $array = array(
        // ...
    );
    $object = (object) $array;
    
  3. Manually convert the array into an object:

    $object = object;
    foreach ($arr as $key => $value) {
        $object->{$key} = $value;
    }
    
  1. 伪造一个真实的对象:

    class convert
    {
        public $varible;
    
        public function __construct($array)
        {
            $this = $array;
        }
    
        public static function toObject($array)
        {
            $array = new convert($array);
            return $array;
        }
    }
    
  2. 通过将数组转换为对象来将数组转换为对象:

    $array = array(
        // ...
    );
    $object = (object) $array;
    
  3. 手动将数组转换为对象:

    $object = object;
    foreach ($arr as $key => $value) {
        $object->{$key} = $value;
    }
    

回答by star18bit

Its way to simple, This will create an object for recursive arrays as well:

它的方法很简单,这也将为递归数组创建一个对象:

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

回答by hakre

Depending on where you need that and how to access the object there are different ways to do it.

根据您需要的位置以及访问对象的方式,有不同的方法可以做到。

For example: just typecast it

例如:只需对其进行类型转换

$object =  (object) $yourArray;

However, the most compatible one is using a utility method (not yet part of PHP) that implements standard PHP casting based on a string that specifies the type (or by ignoring it just de-referencing the value):

然而,最兼容的方法是使用一种实用方法(还不是 PHP 的一部分),该方法基于指定类型的字符串(或通过忽略它只是取消引用值)实现标准 PHP 转换:

/**
 * dereference a value and optionally setting its type
 *
 * @param mixed $mixed
 * @param null  $type (optional)
 *
 * @return mixed $mixed set as $type
 */
function rettype($mixed, $type = NULL) {
    $type === NULL || settype($mixed, $type);
    return $mixed;
}

The usage example in your case (Online Demo):

您的案例中的使用示例(在线演示):

$yourArray = Array('status' => 'Figure A. ...');

echo rettype($yourArray, 'object')->status; // prints "Figure A. ..."

回答by zombat

There's no built-in method to do it as far as I'm aware, but it's as easy as a simple loop:

据我所知,没有内置方法可以做到这一点,但它就像一个简单的循环一样简单:

    $obj= new stdClass();

    foreach ($array as $k=> $v) {
        $obj->{$k} = $v;
    }

You can expound on that if you need it to build your object recursively.

如果您需要它来递归构建您的对象,您可以详细说明。

回答by Noha Shehab

You can use the (object) function to convert your array into an object.

您可以使用 (object) 函数将数组转换为对象。

$arr= [128=> ['status'=>
                 'Figure A. Facebook \'s horizontal scrollbars showing up on a 1024x768 screen resolution.'],
                  129=>['status'=>'The other day at work, I had some spare time']];

            $ArrToObject=(object)$arr;
            var_dump($ArrToObject);

The result will be an object that contains arrays:

结果将是一个包含数组的对象:

object(stdClass)#1048 (2) { [128]=> array(1) {

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

[129]=> array(1) { ["status"]=> string(44) "The other day at work, I had some spare time" } }

object(stdClass)#1048 (2) { [128]=> array(1) {

["status"]=> string(87) "图 A. Facebook 的水平滚动条显示在 1024x768 的屏幕分辨率上。" }

[129]=> array(1) { ["status"]=> string(44) "前几天在工作,我有一些空闲时间" } }