How to convert an array to object in PHP?

2018-12-31 07:56发布

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
        )

)

30条回答
情到深处是孤独
2楼-- · 2018-12-31 08:46

Best Method in the WORLD :)

function arrayToObject($conArray)
{
    if(is_array($conArray)){
        /*
        * Return array converted to object
        * Using __FUNCTION__ (Magic constant)
        * for recursive call
        */
        return (object) array_map(__FUNCTION__, $conArray);
    }else{
        // Return object
        return $conArray;
    }
}

if you use different methods you will have problems. This is the best method. You have ever seen.

查看更多
千与千寻千般痛.
3楼-- · 2018-12-31 08:46

one liner

$object= json_decode(json_encode($result_array, JSON_FORCE_OBJECT));
查看更多
姐姐魅力值爆表
4楼-- · 2018-12-31 08:48

Actually if you want to use this with multi-dimensional arrays you would want to use some recursion.

static public function array_to_object(array $array)
{
    foreach($array as $key => $value)
    {
        if(is_array($value))
        {
            $array[$key] = self::array_to_object($value);
        }
    }
    return (object)$array;
}
查看更多
余生无你
5楼-- · 2018-12-31 08:49

recursion is your friend:

function __toObject(Array $arr) {
    $obj = new stdClass();
    foreach($arr as $key=>$val) {
        if (is_array($val)) {
            $val = __toObject($val);
        }
        $obj->$key = $val;
    }

    return $obj;
}
查看更多
呛了眼睛熬了心
6楼-- · 2018-12-31 08:50

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 Medina pointed out, a really clean solution is to use the built-in json_ functions:

$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 hit over the looping approach.

Warning! (thanks to Ultra for the comment):

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

查看更多
与风俱净
7楼-- · 2018-12-31 08:50

I use the following to parse Yaml files associative arrays into an object state.

This checks all supplied arrays if there are objects hiding there, and turns them also in objects.

    /**
     * Makes a config object from an array, making the first level keys properties a new object.
     * Property values are converted to camelCase and are not set if one already exists.
     * @param array $configArray Config array.
     * @param boolean $strict To return an empty object if $configArray is not an array
     * @return stdObject The config object
     */
    public function makeConfigFromArray($configArray = [],$strict = true)
    {
        $object = new stdClass();

        if (!is_array($configArray)) {
            if(!$strict && !is_null($configArray)) {
                return $configArray;
            }
            return $object;
        }

        foreach ($configArray as $name => $value) {
            $_name = camel_case($name);
            if(is_array($value)) {
                $makeobject = true;
                foreach($value as $key => $val) {
                    if(is_numeric(substr($key,0,1))) {
                        $makeobject = false;
                    }
                    if(is_array($val)) {
                        $value[$key] = $this->makeConfigFromArray($val,false);
                    }
                }
                if($makeobject) {
                    $object->{$name} = $object->{$_name} = $this->makeConfigFromArray($value,false);
                }
                else {
                    $object->{$name} = $object->{$_name} = $value;
                }

            }
            else {
                $object->{$name} = $object->{$_name} = $value;
            }
        }

        return $object;
    }

This turns a yaml configured as

fields:
    abc:
        type: formfield
        something:
            - a
            - b
            - c
            - d:
                foo: 
                   bar

to an array consisting of:

array:1 [
  "fields" => array:1 [
    "abc" => array:2 [
      "type" => "formfield"
      "something" => array:4 [
        0 => "a"
        1 => "b"
        2 => "c"
        3 => array:1 [
          "d" => array:1 [
            "foo" => "bar"
          ]
        ]
      ]
    ]
  ]
]

to an object of:

{#325
  +"fields": {#326
    +"abc": {#324
      +"type": "formfield"
      +"something": array:4 [
        0 => "a"
        1 => "b"
        2 => "c"
        3 => {#328
          +"d": {#327
            +"foo": "bar"
          }
        }
      ]
    }
  }
}
查看更多
登录 后发表回答