Rumah >pembangunan bahagian belakang >tutorial php >PHP中索引数组如何给对象赋值?

PHP中索引数组如何给对象赋值?

WBOY
WBOYasal
2016-06-06 20:09:411540semak imbas

现有对象定义如下:

<code class="php">class User
{
    public $name;
    public $age;
    public $sex;
    public $info;
    public $school;
    public $salary;
}</code>

现有索引数组如下:

<code class="php">$user = [
    'name' => 'zhangsan',
    'age' => 18,
    'sex' => 1,
    'school' => 'sysu',
];</code>

问题是,如何用这个数组给对象赋值,能不能用foreach进行赋值啊?现在我只会下面的实现,但是被说这个方法不好,应该用foreach,但是不知道怎么用?

<code class="php">$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'];</code>

回复内容:

现有对象定义如下:

<code class="php">class User
{
    public $name;
    public $age;
    public $sex;
    public $info;
    public $school;
    public $salary;
}</code>

现有索引数组如下:

<code class="php">$user = [
    'name' => 'zhangsan',
    'age' => 18,
    'sex' => 1,
    'school' => 'sysu',
];</code>

问题是,如何用这个数组给对象赋值,能不能用foreach进行赋值啊?现在我只会下面的实现,但是被说这个方法不好,应该用foreach,但是不知道怎么用?

<code class="php">$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'];</code>

<code>foreach($user as $prop => $val) {
    $user1->{$prop} = $val;
}</code>

<code>
    $userObj = new User();
    foreach($user as $key => $value){
        if(property_exists($userObj,$key)){
            $userObj->$key = $value
        }
    }</code>

<code>$user = [
    'name' => 'zhangsan',
    'age' => 18,
    'sex' => 1,
    'school' => 'sysu',
];

$userobj = (object)$user</code>
Kenyataan:
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Artikel sebelumnya:sphinx能做关键词统计吗?Artikel seterusnya:phpstorm打开出错