5

当具有私有变量的对象已转换(转换)为 php 中的数组时,数组元素键将以

*_

. 如何删除存在于数组键开头的“*_”?

例如

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

投射后的数组

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

我想

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

4 回答 4

10

我是这样做的

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();
于 2012-07-04T14:41:58.793 回答
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();
于 2012-06-07T09:29:53.260 回答
2

您可能会遇到问题,因为您正在访问其允许范围之外的私有变量。

尝试更改为:

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

或者,一个黑客:

foreach($array as $key => $val)
{
   $new_array[str_replace('*_','',$key)] = $val;
}
于 2012-06-07T09:11:58.437 回答
1

以下是将对象转换为数组的步骤

1)。将对象转换为数组

2)。将数组转换为 json 字符串。

3)。替换字符串以删除“*_”

e.g
    $strArr= str_replace('\u0000*\u0000_','',json_encode($arr));
    $arr = json_decode($strArr);
于 2014-07-31T07:17:08.073 回答