Convert a PHP object to an associative array

后端 未结 30 2037
走了就别回头了
走了就别回头了 2020-11-22 02:18

I\'m integrating an API to my website which works with data stored in objects while my code is written using arrays.

I\'d like a quick-and-dirty function to convert

30条回答
  •  没有蜡笔的小新
    2020-11-22 02:44

    First of all, if you need an array from an object you probably should constitute the data as an array first. Think about it.

    Don't use a foreach statement or JSON transformations. If you're planning this, again you're working with a data structure, not with an object.

    If you really need it use an object-oriented approach to have a clean and maintainable code. For example:

    Object as array

    class PersonArray implements \ArrayAccess, \IteratorAggregate
    {
        public function __construct(Person $person) {
            $this->person = $person;
        }
        // ...
     }
    

    If you need all properties, use a transfer object:

    class PersonTransferObject
    {
        private $person;
    
        public function __construct(Person $person) {
            $this->person = $person;
        }
    
        public function toArray() {
            return [
                // 'name' => $this->person->getName();
            ];
        }
    
     }
    

提交回复
热议问题