當與私有變量一個對象,已轉換(澆鑄)到陣列在php數組元素的鍵將與PHP轉換對象陣列
* _
啓動。如何刪除數組鍵的開頭存在的「* _」?
例如
class Book {
private $_name;
private $_price;
}
鑄造
array('*_name' => 'abc', '*_price' => '100')
陣列後,我想
array('name' => 'abc', 'price' => '100')
當與私有變量一個對象,已轉換(澆鑄)到陣列在php數組元素的鍵將與PHP轉換對象陣列
* _
啓動。如何刪除數組鍵的開頭存在的「* _」?
例如
class Book {
private $_name;
private $_price;
}
鑄造
array('*_name' => 'abc', '*_price' => '100')
陣列後,我想
array('name' => 'abc', 'price' => '100')
我做了這樣
class Book {
private $_name;
private $_price;
public function toArray() {
$vars = get_object_vars ($this);
$array = array();
foreach ($vars as $key => $value) {
$array [ltrim ($key, '_')] = $value;
}
return $array;
}
}
,當我想要一本書轉換對象到數組我調用toArray()函數
$book->toArray();
要做到這一點,你還是應該實現在類中toArray()
方法。這樣,您可以保護您的屬性並仍然可以訪問屬性數組。
有很多方法可以實現這一點,如果將對象數據作爲數組傳遞給構造函數,以下是一種有用的方法。
//pass an array to constructor
public function __construct(array $options = NULL) {
//if we pass an array to the constructor
if (is_array($options)) {
//call setOptions() and pass the array
$this->setOptions($options);
}
}
public function setOptions(array $options) {
//an array of getters and setters
$methods = get_class_methods($this);
//loop through the options array and call setters
foreach ($options as $key => $value) {
//here we build an array of values as we set properties.
$this->_data[$key] = $value;
$method = 'set' . ucfirst($key);
if (in_array($method, $methods)) {
$this->$method($value);
}
}
return $this;
}
//just return the array we built in setOptions
public function toArray() {
return $this->_data;
}
你也可以用你的getter和代碼,以使陣列看你想怎麼創建數組。你也可以使用__set()和__get()來完成這個工作。
當一切都說過和做過的目標將有一些作品,如:
//instantiate an object
$book = new Book(array($values);
//turn object into an array
$array = $book->toArray();
這裏是C將對象轉換爲陣列
1)。將對象轉換爲陣列
2)。將數組轉換爲json字符串。 3)。替換字符串刪除「* _」
e.g
$strArr= str_replace('\u0000*\u0000_','',json_encode($arr));
$arr = json_decode($strArr);
感謝您的簡單的一班。必須在json_decode上設置返回關聯數組的標誌,否則我們會返回一個對象。 – Laoneo
方便,我不知道get_object_vars。我知道必須有一種將基本對象轉換爲數組的簡單方法。謝謝! – David
工作良好,除非我有遞歸對象 – Dennis