Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

array of arrays to array of objects php

Tags:

arrays

object

php

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.

like image 555
Matthew Sprankle Avatar asked Jul 17 '26 22:07

Matthew Sprankle


1 Answers

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.

like image 155
jmkeyes Avatar answered Jul 19 '26 11:07

jmkeyes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!