I am trying to convert the associative array to an array of objects.
$assoc = array (
array(
'prop1'=>'val1',
'prop2'=>'val2',
),
array(
'prop1'=>'val1',
'prop2'=>'val2',
),
)
Here Is the code I have so far:
class Assoc {
public function setObject($assoc) {
$this->assoc[] = new Obj($assoc);
}
}
class Obj {
public function __construct($item) {
foreach ( $item as $property=>$value ) {
$this->{$property} = $value;
}
}
}
$test = New Assoc();
$test->setObject($assoc);
This code will work for a single array but not an array of arrays. If you could help with what I believe to be the loop in the setObject function.
Convert the associative array to an array of objects:
$output = array_map(function($element) {
return (object) $element;
}, $assoc);
Simple enough.
EDIT: If you need to make objects of a specific class:
$output = array_map(function($element) use ($classType) {
return new $classType($element);
}, $assoc);
You can generalize it into just about anything, really.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With