The existing object is defined as follows: {code...} the existing index array is as follows: {code...} the question is, how can I assign a value to an object using this array? Can I assign a value using foreach? Now I only use the following implementation, but I am told that this method is not good. I should use foreach, but I don't know how to use it? {... The existing object is defined as follows:
class User{ public $name; public $age; public $sex; public $info; public $school; public $salary;}
The existing index array is as follows:
$user = [ 'name' => 'zhangsan', 'age' => 18, 'sex' => 1, 'school' => 'sysu',];
The question is, how can I assign values to objects using this array? Can I assign values using foreach? Now I only use the following implementation, but I am told that this method is not good. I should use foreach, but I don't know how to use it?
$user1 = new User();if(isset($user['name'])) $user1->name = $user['name'];if(isset($user['age'])) $user1->age = $user['age'];if(isset($user['sex'])) $user1->sex = $user['sex'];if(isset($user['info'])) $user1->info = $user['info'];if(isset($user['school'])) $user1->school = $user['school'];if(isset($user['salary'])) $user1->salary = $user['salary'];
Reply content:
Existing objects are defined as follows:
class User{ public $name; public $age; public $sex; public $info; public $school; public $salary;}
The existing index array is as follows:
$user = [ 'name' => 'zhangsan', 'age' => 18, 'sex' => 1, 'school' => 'sysu',];
The question is, how can I assign values to objects using this array? Can I assign values using foreach? Now I only use the following implementation, but I am told that this method is not good. I should use foreach, but I don't know how to use it?
$user1 = new User();if(isset($user['name'])) $user1->name = $user['name'];if(isset($user['age'])) $user1->age = $user['age'];if(isset($user['sex'])) $user1->sex = $user['sex'];if(isset($user['info'])) $user1->info = $user['info'];if(isset($user['school'])) $user1->school = $user['school'];if(isset($user['salary'])) $user1->salary = $user['salary'];
foreach($user as $prop => $val) { $user1->{$prop} = $val;}
$userObj = new User(); foreach($user as $key => $value){ if(property_exists($userObj,$key)){ $userObj->$key = $value } }
$user = [ 'name' => 'zhangsan', 'age' => 18, 'sex' => 1, 'school' => 'sysu',];$userobj = (object)$user