PHP将对象转换为数组
当带有私有变量的对象在php中转换(cast)为数组时,数组元素键将以 *_ 。如何删除数组键开头的“*x” 比如说PHP将对象转换为数组,php,arrays,zend-framework,Php,Arrays,Zend Framework,当带有私有变量的对象在php中转换(cast)为数组时,数组元素键将以 *_ 。如何删除数组键开头的“*x” 比如说 class Book { private $_name; private $_price; } 铸造后的阵列 array('*_name' => 'abc', '*_price' => '100') 我想要 array('name' => 'abc', 'price' => '100') 您可能会遇到问题,因为您正在访问其允许范围之外
class Book {
private $_name;
private $_price;
}
铸造后的阵列
array('*_name' => 'abc', '*_price' => '100')
我想要
array('name' => 'abc', 'price' => '100')
您可能会遇到问题,因为您正在访问其允许范围之外的私有变量 尝试更改为:
class Book {
public $_name;
public $_price;
}
或者,黑客:
foreach($array as $key => $val)
{
$new_array[str_replace('*_','',$key)] = $val;
}
要正确地执行此操作,您需要在类中实现
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和代码构建一个数组,以使数组符合您的要求。您还可以使用uuu set()和uuu get()来实现此功能。当一切都说了又做了的时候,我们的目标就是要有这样的东西:
//instantiate an object
$book = new Book(array($values);
//turn object into an array
$array = $book->toArray();
我是这样做的
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;
}
}
当我想将book对象转换为数组时,我调用toArray()函数
以下是将对象转换为数组的步骤 1) 。将对象转换为数组 2) 。将数组转换为json字符串 3) 。替换字符串以删除“*"”
不,我只想删除数组中的*u,实现我建议的编辑是不可能的,因为我只通过getter和setter(封装)访问变量。您似乎没有将
$
放在变量之前,并使用适当的隐私范围。我已经包括了一个可以为你重置数组键的黑客程序。Handy,我不知道get_object_vars。我知道必须有一种简单的方法将基本对象转换为数组。谢谢谢谢你简单的一行。必须在json_decode上设置返回关联数组的标志,否则我们将返回一个对象。
$book->toArray();
e.g
$strArr= str_replace('\u0000*\u0000_','',json_encode($arr));
$arr = json_decode($strArr);