如何将 php 对象转换为数组?
在 php 中,如果获取到类似以下数据库数据:
object(thinkcollection)#117 (1) { ["items":protected] => array(10) { [0] => array(5) { ["id"] => int(2) ["post_id"] => int(7) ["category_id"] => int(9) ["list_order"] => float(10000) ["status"] => int(1) } // ... 还有其他 9 个数组元素 } }
并希望将其转换为数组怎么办?
解决方案:
遇到这种情况时,可以调用 toarray 方法:
$data->toarray();
toarray 方法会将集合对象转换为标准 php 数组。
示例:
$data = object(thinkcollection)#117 (1) { ["items":protected] => array(10) { // ... 内容与上面相同 } }; var_dump($data->toarray());
输出结果:
array(10) { [0] => array(5) { ["id"] => int(2) ["post_id"] => int(7) ["category_id"] => int(9) ["list_order"] => float(10000) ["status"] => int(1) } // ... 还有其他 9 个数组元素 }