How to convert an array to object in PHP?

前端 未结 30 2818
说谎
说谎 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. ..."
    

提交回复
热议问题