我正在尝试将关联数组转换为对象数组。
$assoc = array (
array(
'prop1'=>'val1',
'prop2'=>'val2',
),
array(
'prop1'=>'val1',
'prop2'=>'val2',
),
)以下是我到目前为止拥有的代码:
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);此代码将适用于单个数组,但不适用于数组的数组。如果你能帮我解决我认为是setObject函数中的循环。
发布于 2012-01-14 14:42:57
特定对象的编辑:
要尽可能地保持现有的风格,而又不影响array_map伏都教:
class Assoc {
public function setObject($assoc) {
foreach ($assoc as $arr) {
$this->assoc[] = new Obj($arr);
}
}
}
class Obj {
public function __construct($item) {
foreach ( $item as $property=>$value ) {
$this->{$property} = $value;
}
}
}
$test = New Assoc();
$test->setObject($assoc);原创:
如果您只需要泛型转换,而不是转换为特定的自定义对象(在您的帖子中不是很清楚?)您可以尝试这样做:
$new_array = array();
foreach ($assoc as $to_obj)
{
$new_array[] = (object)$to_obj;
}
// Print results
var_dump($new_array);输出:
array(2) {
[0]=>
object(stdClass)#1 (2) {
["prop1"]=>
string(4) "val1"
["prop2"]=>
string(4) "val2"
}
[1]=>
object(stdClass)#2 (2) {
["prop1"]=>
string(4) "val1"
["prop2"]=>
string(4) "val2"
}
}发布于 2012-01-14 14:45:41
将关联数组转换为对象数组:
$output = array_map(function($element) {
return (object) $element;
}, $assoc);很简单。
编辑:如果需要创建特定类的对象:
$output = array_map(function($element) use ($classType) {
return new $classType($element);
}, $assoc);你可以把它概括为任何东西,真的。
发布于 2012-01-14 14:44:37
$len = count($assoc);
for($i=0;$i<$len; $i++){
$assoc[$i] = (Object)$assoc[$i];
}https://stackoverflow.com/questions/8860623
复制相似问题