在PHP中将数组转换为用户定义的对象

时间:2015-04-28 13:45:00

标签: php arrays xml stdclass user-defined

我有一个数组如下 -

$xml= array(
                'name'=> 'Arun',
                'roll' => '12345',
                'id' => '1'
        );

我希望将其转换为用户定义的对象[非stdClass Nor SimpleXMLObject]

我想要下面的内容 -

UserDefinedObject Object 
(
    [name] => Arun
    [roll] => 12345
    [id] => 1
)

我做了像belo这样的东西,它给了我stdClass对象,但我需要这个是UserDefined -

public static function convert($xml)
    {
        //$array = new ConvertArrayToXML($xml);
        //return $array;
        //return((Object)$xml);
        foreach($xml as $key => $value)
        {
            if(is_array($value))
            {
                $array[$key] = self::convert($value);
            }
        }
        return (object)$xml;
    }

我知道这可能听起来很愚蠢,但我很擅长在php中投射用户定义的对象。

请给出一些指示。

感谢。

3 个答案:

答案 0 :(得分:1)

$xml = [
    'name'=> 'Arun',
    'roll' => '12345',
    'id' => '1',
];

class UserDefinedObject { }

$myObj = new UserDefinedObject();
foreach($xml as $key => $value) { 
    $myObj->{$key} = $value; 
}

var_dump($myObj);

修改

或略有变化:

$myObj = new UserDefinedObject();
array_walk($xml,
    function($value, $key) use ($myObj) {
        $myObj->{$key} = $value; 
    }
);

答案 1 :(得分:1)

class UserDefinedClass {
public $name;
public $roll;
public $id;

    function __construct($name,$roll,$id){
        $this->name = $name;
        $this->roll = $roll;
        $this->id = $id;
    }
}
$xml= array(
     'name'=> 'Arun',
     'roll' => '12345',
     'id' => '1'
);


$obj = new UserDefinedClass($xml['name'],$xml['roll'],$xml['id']);
// you can use and foreach for dynamic elements.
print_r($obj);

答案 2 :(得分:0)

$ xml = array('name'=>'Arun','roll'=>'12345','id'=>'1');

类UserDefined {

public $name;
public $roll;
public $id;

function __construct($xml) {
    $this->name = $xml['name'];
    $this->roll = $xml['roll'];
    $this->id = $xml['id'];
}

}

print_r(new UserDefined($ xml));