How to convert an array to object in PHP?

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

    Here are three ways:

    1. Fake a real object:

      class convert
      {
          public $varible;
      
          public function __construct($array)
          {
              $this = $array;
          }
      
          public static function toObject($array)
          {
              $array = new convert($array);
              return $array;
          }
      }
      
    2. Convert the array into an object by casting it to an object:

      $array = array(
          // ...
      );
      $object = (object) $array;
      
    3. Manually convert the array into an object:

      $object = object;
      foreach ($arr as $key => $value) {
          $object->{$key} = $value;
      }
      

提交回复
热议问题