How to convert an array to object in PHP?

前端 未结 30 2840
说谎
说谎 2020-11-22 02:48

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

[128] => Array
    (
        [status] => "Figure A.
 Facebook\'s horizontal scrollbars showing u         


        
相关标签:
30条回答
  • 2020-11-22 03:16

    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):

    /**
     * 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. ..."
    
    0 讨论(0)
  • 2020-11-22 03:16

    You can use Reflection:

    <?php
    
    $array = ['name'=>'maria','age'=>33];
    
    class Person {
    
        public $name;
        public $age;
    
        public function __construct(string $name, string $age){
            $this->name  = $name;
            $this->age = $age;
        }
    }
    
    function arrayToObject(array $array, string $class_name){
    
        $r = new ReflectionClass($class_name);
        $object = $r->newInstanceWithoutConstructor();
        $list = $r->getProperties();
        foreach($list as $prop){
          $prop->setAccessible(true);
          if(isset($array[$prop->name]))
            $prop->setValue($object, $array[$prop->name]);
        } 
    
        return $object;
    
    }
    
    $pessoa1 = arrayToObject($array, 'Person');
    var_dump($pessoa1);
    
    0 讨论(0)
  • 2020-11-22 03:18

    Quick hack:

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

    Not pretty, but works.

    0 讨论(0)
  • 2020-11-22 03:20

    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;
    }
    
    0 讨论(0)
  • 2020-11-22 03:20

    Using json_encode is problematic because of the way that it handles non UTF-8 data. It's worth noting that the json_encode/json_encode method also leaves non-associative arrays as arrays. This may or may not be what you want. I was recently in the position of needing to recreate the functionality of this solution but without using json_ functions. Here's what I came up with:

    /**
     * Returns true if the array has only integer keys
     */
    function isArrayAssociative(array $array) {
        return (bool)count(array_filter(array_keys($array), 'is_string'));
    }
    
    /**
     * Converts an array to an object, but leaves non-associative arrays as arrays. 
     * This is the same logic that `json_decode(json_encode($arr), false)` uses.
     */
    function arrayToObject(array $array, $maxDepth = 10) {
        if($maxDepth == 0) {
            return $array;
        }
    
        if(isArrayAssociative($array)) {
            $newObject = new \stdClass;
            foreach ($array as $key => $value) {
                if(is_array($value)) {
                    $newObject->{$key} = arrayToObject($value, $maxDepth - 1);
                } else {
                    $newObject->{$key} = $value;
                }
            }
            return $newObject;
        } else {
    
            $newArray = array();
            foreach ($array as $value) {
                if(is_array($value)) {
                    $newArray[] = arrayToObject($value, $maxDepth - 1);
                } else {
                    $newArray[] = $value;
                }                
            }
            return $newArray;
        }
    }
    
    0 讨论(0)
  • 2020-11-22 03:21

    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;
    }
    
    0 讨论(0)
提交回复
热议问题