Convert PHP object to associative array

2018-12-31 05:31发布

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 an object to an array.

标签: php arrays
27条回答
闭嘴吧你
2楼-- · 2018-12-31 06:24

Also you can use The Symfony Serializer Component

use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Serializer;

$serializer = new Serializer([new ObjectNormalizer()], [new JsonEncoder()]);
$array = json_decode($serializer->serialize($object, 'json'), true);
查看更多
不流泪的眼
3楼-- · 2018-12-31 06:25
class Test{
    const A = 1;
    public $b = 'two';
    private $c = test::A;

    public function __toArray(){
        return call_user_func('get_object_vars', $this);
    }
}

$my_test = new Test();
var_dump((array)$my_test);
var_dump($my_test->__toArray());

Output

array(2) {
    ["b"]=>
    string(3) "two"
    ["Testc"]=>
    int(1)
}
array(1) {
    ["b"]=>
    string(3) "two"
}
查看更多
余生请多指教
4楼-- · 2018-12-31 06:25

Here I've made an objectToArray() method, which also works with recursive objects, like when $objectA contains $objectB which points again to $objectA.

Additionally I've restricted the output to public properties using ReflectionClass. Get rid of it, if you don't need it.

    /**
     * Converts given object to array, recursively.
     * Just outputs public properties.
     *
     * @param object|array $object
     * @return array|string
     */
    protected function objectToArray($object) {
        if (in_array($object, $this->usedObjects, TRUE)) {
            return '**recursive**';
        }
        if (is_array($object) || is_object($object)) {
            if (is_object($object)) {
                $this->usedObjects[] = $object;
            }
            $result = array();
            $reflectorClass = new \ReflectionClass(get_class($this));
            foreach ($object as $key => $value) {
                if ($reflectorClass->hasProperty($key) && $reflectorClass->getProperty($key)->isPublic()) {
                    $result[$key] = $this->objectToArray($value);
                }
            }
            return $result;
        }
        return $object;
    }

To identify already used objects, I am using a protected property in this (abstract) class, named $this->usedObjects. If a recursive nested object is found, it will be replaced by the string **recursive**. Otherwise it would fail in because of infinite loop.

查看更多
骚的不知所云
5楼-- · 2018-12-31 06:26

Converting and removing annoying stars :

$array = (array) $object;
foreach($array as $key => $val)
{
   $new_array[str_replace('*_','',$key)] = $val;
}

Probably, it will be cheaper than using reflections.

查看更多
忆尘夕之涩
6楼-- · 2018-12-31 06:29

You might want to do this when you obtain data as objects from databases -->

// Suppose result is the end product from some query $query

$result = $mysqli->query($query);
$result = db_result_to_array($result);

function db_result_to_array($result)
{
$res_array = array();

for ($count=0; $row = $result->fetch_assoc(); $count++)
    $res_array[$count] = $row;

    return $res_array;
}
查看更多
若你有天会懂
7楼-- · 2018-12-31 06:30

To convert an object into array just cast it explicitly

$name_of_array =  (array) $name_of_object;
查看更多
登录 后发表回答