php read mongodb.findone()返回json值并创建对象

时间:2014-04-08 10:06:04

标签: php json mongodb object

我有一个员工类,我想从mongodb.findone()返回的数组初始化员工对象。

foreach($res as $key => $value){
    echo $value; // here values printed
}

但是我需要做一些事情(如果key =' first_name'那么employee_obj-> set_first_name($ value),如果key =' last_name'那么employee_obj-> set_last_name ($ value)...)你能帮助我吗?

2 个答案:

答案 0 :(得分:0)

$employee = new Employee;

foreach($res as $key => $value){
    if (property_exists($employee, $key)) {
        $employee->$key = $value;
    }
}

$employee->$key = $value正在为员工动态分配$key属性。例如:

    $key = "name";
    $employee->$key = "John Doe";
    echo $employee->name; // John Doe

如果您想使用私有或受保护的属性执行此操作,则需要在类或实例中进行分配:

class Employee {

    // ...
    private $name;

    // lets you assign properties by passing in an array
    public function __construct($arr = array()){
        if count($arr) {
            foreach($arr as $key => $value){
                if (property_exists($this, $key)) {
                    $this->$key = $value;
                }
            }
        }
    }
}

$joe = new Employee(array('name' => 'Joe'));
echo $joe->name // Joe

答案 1 :(得分:0)

$e = new Employee;
foreach($res as $k => $v){
    if($k == 'first_name'){
        $e->set_first_name($v);
    }elseif($k == 'last_name'){
        $e->set_last_name($v);
    }else{
        $e->$k = $v;
    }
}

正是这样。