简体   繁体   中英

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.

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?

$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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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