您好,登錄后才能下訂單哦!
這篇文章主要介紹了如何用php將對(duì)象轉(zhuǎn)化為數(shù)組的相關(guān)知識(shí),內(nèi)容詳細(xì)易懂,操作簡(jiǎn)單快捷,具有一定借鑒價(jià)值,相信大家閱讀完這篇如何用php將對(duì)象轉(zhuǎn)化為數(shù)組文章都會(huì)有所收獲,下面我們一起來看看吧。
1.使用get_object_vars()函數(shù)
PHP提供了get_object_vars()函數(shù),它可以將對(duì)象的屬性值轉(zhuǎn)化為一個(gè)關(guān)聯(lián)數(shù)組。這個(gè)函數(shù)接收一個(gè)對(duì)象作為參數(shù),并返回一個(gè)數(shù)組,數(shù)組的鍵是對(duì)象屬性的名稱,數(shù)組的值是屬性的值。下面是一個(gè)例子:
class Person {
public $name;
public $age;
public $gender;
public function __construct($name, $age, $gender) {
$this->name = $name;
$this->age = $age;
$this->gender = $gender;
}
}
$person = new Person('Tom', 18, 'male');
$arr = get_object_vars($person);
print_r($arr);
輸出結(jié)果為:
Array
(
[name] => Tom
[age] => 18
[gender] => male
)
2.使用json_encode()函數(shù)
除了使用get_object_vars()函數(shù)之外,我們還可以使用json_encode()函數(shù)將對(duì)象轉(zhuǎn)換為JSON格式的字符串,然后使用json_decode()函數(shù)將其轉(zhuǎn)換為數(shù)組。下面是一個(gè)例子:
class Person {
public $name;
public $age;
public $gender;
public function __construct($name, $age, $gender) {
$this->name = $name;
$this->age = $age;
$this->gender = $gender;
}
}
$person = new Person('Tom', 18, 'male');
$jsonStr = json_encode($person);
$arr = json_decode($jsonStr, true);
print_r($arr);
輸出結(jié)果和上一個(gè)例子相同。
3.使用對(duì)象的__toArray()方法
如果你掌握了面向?qū)ο缶幊痰幕A(chǔ)知識(shí),那么你可以在自己的類中定義一個(gè)__toArray()方法,該方法用于將對(duì)象的屬性值轉(zhuǎn)化為一個(gè)數(shù)組。下面是一個(gè)例子:
class Person {
public $name;
public $age;
public $gender;
public function __construct($name, $age, $gender) {
$this->name = $name;
$this->age = $age;
$this->gender = $gender;
}
public function __toArray() {
$arr = [];
$arr['name'] = $this->name;
$arr['age'] = $this->age;
$arr['gender'] = $this->gender;
return $arr;
}
}
$person = new Person('Tom', 18, 'male');
$arr = $person->__toArray();
print_r($arr);
輸出結(jié)果也和前面兩個(gè)例子相同。
關(guān)于“如何用php將對(duì)象轉(zhuǎn)化為數(shù)組”這篇文章的內(nèi)容就介紹到這里,感謝各位的閱讀!相信大家對(duì)“如何用php將對(duì)象轉(zhuǎn)化為數(shù)組”知識(shí)都有一定的了解,大家如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。