简体   繁体   English

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

[英]php read mongodb.findone() returned json values and create object

I have an employee class and i want to initialize the employee object from mongodb.findone() returned array. 我有一个雇员类,我想从mongodb.findone()返回的数组初始化雇员对象。

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

but i need to do something like( if key = 'first_name' then employee_obj->set_first_name($value), if key = 'last_name' then employee_obj->set_last_name($value)... ) can you help me? 但是我需要做一些类似的事情(如果key ='first_name'然后employee_obj-> set_first_name($ value),如果key ='last_name'然后employee_obj-> set_last_name($ value)...)能帮我吗?

$employee = new Employee;

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

$employee->$key = $value is dynamically assigning $key property to the employee. $employee->$key = $value为雇员动态分配$key属性。 Example: 例:

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

If you want to do this with private or protected properties you need to do the assignment within the class or instance: 如果要使用私有或受保护的属性执行此操作,则需要在类或实例内进行分配:

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
$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;
    }
}

Does exactly that. 确实做到了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM