PHP简单 对象(object) 与 数组(array) 的转换

//数组转换对象

function array_to_object($arr) {
    if (gettype($arr) != 'array') {
        return ;
    }
    foreach ($arr as $k => $v) {
        if (gettype($v) == 'array' || gettype($v) == 'object') {
            $arr[$k] = (object)array_to_object($v);
        }
    }
    return (object)$arr;
}
//对象转换数组
function object_to_array($obj) {
    $obj = (array)$obj;
    foreach ($obj as $k => $v) {
        if (gettype($v) == 'resource') {
            return ;
        }
        if (gettype($v) == 'object' || gettype($v) == 'array') {
            $obj[$k] = (array)object_to_array($v);
        }
    }
    return $obj;
}

$arr = [['zhangsan','man'], ['lisi','man'], ['lisa','women']];
var_dump(array_to_object($arr));
var_dump(object_to_array($arr));

标签: none

添加新评论