2012-06-07 213 views
2

當與私有變量一個對象,已轉換(澆鑄)到陣列在php數組元素的鍵將與PHP轉換對象陣列

* _

啓動。如何刪除數組鍵的開頭存在的「* _」?

例如

class Book { 
    private $_name; 
    private $_price; 
} 

鑄造

array('*_name' => 'abc', '*_price' => '100') 

陣列後,我想

array('name' => 'abc', 'price' => '100') 

回答

5

我做了這樣

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(); 
+0

方便,我不知道get_object_vars。我知道必須有一種將基本對象轉換爲數組的簡單方法。謝謝! – David

+0

工作良好,除非我有遞歸對象 – Dennis

3

你可能遇到了問題,因爲你所訪問的外私有變量自己允許的範圍。

嘗試改用:

class Book { 
    public $_name; 
    public $_price; 
} 

或者,一個黑客:

foreach($array as $key => $val) 
{ 
    $new_array[str_replace('*_','',$key)] = $val; 
} 
+0

沒有,我只是想刪除* _數組中 – Sachindra

+0

嘗試實現我所推薦的 – hohner

+0

因爲我只能通過getter和setter方法訪問這些變量是不可能的(封裝)。 – Sachindra

3

要做到這一點,你還是應該實現在類中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(); 
1

這裏是C將對象轉換爲陣列

1)。將對象轉換爲陣列

2)。將數組轉換爲json字符串。 3)。替換字符串刪除「* _」

e.g 
    $strArr= str_replace('\u0000*\u0000_','',json_encode($arr)); 
    $arr = json_decode($strArr); 
+0

感謝您的簡單的一班。必須在json_decode上設置返回關聯數組的標誌,否則我們會返回一個對象。 – Laoneo