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

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. ..."
查看更多
长期被迫恋爱
3楼-- · 2018-12-31 08:24

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.

查看更多
牵手、夕阳
4楼-- · 2018-12-31 08:25

The one I use (it is a class member):

const MAX_LEVEL = 5; // change it as needed

public function arrayToObject($a, $level=0)
{

    if(!is_array($a)) {
        throw new InvalidArgumentException(sprintf('Type %s cannot be cast, array expected', gettype($a)));
    }

    if($level > self::MAX_LEVEL) {
        throw new OverflowException(sprintf('%s stack overflow: %d exceeds max recursion level', __METHOD__, $level));
    }

    $o = new stdClass();
    foreach($a as $key => $value) {
        if(is_array($value)) { // convert value recursively
            $value = $this->arrayToObject($value, $level+1);
        }
        $o->{$key} = $value;
    }
    return $o;
}
查看更多
一个人的天荒地老
5楼-- · 2018-12-31 08:25

This requires PHP7 because I chose to use a lambda function to lock away the 'innerfunc' within the main function. The lambda function is called recursively, hence the need for: "use ( &$innerfunc )". You could do it in PHP5 but could not hide the innerfunc.

function convertArray2Object($defs) {
    $innerfunc = function ($a) use ( &$innerfunc ) {
       return (is_array($a)) ? (object) array_map($innerfunc, $a) : $a; 
    };
    return (object) array_map($innerfunc, $defs);
}
查看更多
美炸的是我
6楼-- · 2018-12-31 08:26

Obviously just an extrapolation of some other folks' answers, but here's the recursive function that will convert any mulch-dimensional array into an object:

   function convert_array_to_object($array){
      $obj= new stdClass();
      foreach ($array as $k=> $v) {
         if (is_array($v)){
            $v = convert_array_to_object($v);   
         }
         $obj->{strtolower($k)} = $v;
      }
      return $obj;
   }

And remember that if the array had numeric keys they can still be referenced in the resulting object by using {} (for instance: $obj->prop->{4}->prop)

查看更多
浪荡孟婆
7楼-- · 2018-12-31 08:27

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;
    }
}
查看更多
登录 后发表回答