php - Populating an object's properties with an array? -
I want to take an array and use the array's names to populate the values of that array in the properties of the array. Want to Like:
$ a = array ('property1' => 1, 'property2' => 2); $ O = new Obj (); $ O- & gt; Populate ($ one); Class Obj {function populate ($ array) {// ?? }}
After this, I now have:
$ o-> Properties 1 == 1 $ o- & gt; Properties 2 == 2
How would I go about doing this?
foreach ($ one $ key = & gt; $ value) {$ o- & Gt; $ Key = $ value; }
However, the syntax that you are using to declare your array is not valid. You need to do something like this:
$ a = array ('property1' => 1, 'property2' = & gt; 2);
If you do not care about the class of the object, you can do so (by giving you an example of stdClass
):
$ o = (object) $ a;
Comments
Post a Comment