How to convert an array to object in PHP?

前端 未结 30 2686
说谎
说谎 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 02:58

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

    $object = json_decode(json_encode((object) $yourArray), FALSE);
    
    0 讨论(0)
  • 2020-11-22 02:59

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

    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

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

    one liner

    $object= json_decode(json_encode($result_array, JSON_FORCE_OBJECT));
    
    0 讨论(0)
  • 2020-11-22 03:02

    CakePHP has a recursive Set::map class that basically maps an array into an object. You may need to change what the array looks like in order to make the object look the way you want it.

    http://api.cakephp.org/view_source/set/#line-158

    Worst case, you may be able to get a few ideas from this function.

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

    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.

    0 讨论(0)
提交回复
热议问题