PHP - recursive Array to Object?

前端 未结 14 1308
夕颜
夕颜 2020-12-14 14:10

Is there a way to convert a multidimensional array to a stdClass object in PHP?

Casting as (object) doesn\'t seem to work recu

14条回答
  •  余生分开走
    2020-12-14 15:06

    You and many others have pointed to the JSON built-in functions, json_decode() and json_encode(). The method which you have mentioned works, but not completely: it won't convert indexed arrays to objects, and they will remain as indexed arrays. However, there is a trick to overcome this problem. You can use JSON_FORCE_OBJECT constant:

    // Converts an array to an object recursively
    $object = json_decode(json_encode($array, JSON_FORCE_OBJECT));
    

    Tip: Also, as mentioned here, you can convert an object to array recursively using JSON functions:

    // Converts an object to an array recursively
    $array = json_decode(json_encode($object), true));    
    

提交回复
热议问题