将PHP对象转换为数组

5
当一个带有私有变量的对象在php中被转换为数组时,数组元素键将以*_开头。如何删除存在于数组键开头的"*_"呢?例如:
class Book {
    private $_name;
    private $_price;
}

将数组强制转换后的结果
array('*_name' => 'abc', '*_price' => '100')

I want

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

11

我是这样做的

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

很方便,我不知道get_object_vars。我知道一定有一种简单的方法将基本对象转换为数组。谢谢! - David

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

2

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

尝试更改为:

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

或者,一个技巧:
foreach($array as $key => $val)
{
   $new_array[str_replace('*_','',$key)] = $val;
}

不,我只想从数组中删除*_。 - Sachindra
尝试实现我所推荐的内容。 - hohner
这是不可能的,因为我只通过getter和setter方法来访问变量(封装)。 - Sachindra
你似乎没有在变量前面加上 $ 并使用适当的隐私范围。我已经包含了一个 hack,它应该为您重置数组键。 - hohner

1

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

1). 将对象转换为数组。

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

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

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

感谢这个简单的一行代码。在使用json_decode时,必须设置返回关联数组的标志,否则我们将得到一个对象。 - Laoneo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接