How to convert an array to object in PHP?

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

提交回复
热议问题