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;
    }
}

book オブジェクトを配列に変換する場合は、 toArray() 関数を呼び出します

$book->toArray();
于 2012-07-04T14:41:58.793 に答える
3

toArray()これを適切に行うには、クラスにメソッドを実装する必要があります。こうすることで、プロパティを保護したまま、プロパティの配列にアクセスできます。
これを実現するには多くの方法があります。オブジェクト データをコンストラクターに配列として渡す場合に役立つ方法の 1 つを次に示します。

//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 に答える