【发布时间】:2015-12-25 15:17:57
【问题描述】:
我处于将数组映射到对象然后将其分配给另一个数组的情况。只需从嵌套数组中创建一个对象数组。
array (size=2)
0 =>
array (size=3)
'edu_id' => string '3' (length=1)
'edu_degree' => string 'MCA' (length=3)
'edu_institute' => string 'ECB' (length=3)
1 =>
array (size=3)
'edu_id' => string '4' (length=1)
'edu_degree' => string 'BCA' (length=3)
'edu_institute' => string 'CET' (length=3)
这是数组,我正在尝试将它转换成这个 -
array (size=2)
0 =>
object(MatEducation)[11]
private 'id' => int 1
private 'eduId' => string '3' (length=1)
private 'degree' => string 'MCA' (length=3)
private 'institute' => string 'ECB' (length=3)
1 =>
object(MatEducation)[11]
private 'id' => int 1
private 'eduId' => string '4' (length=1)
private 'degree' => string 'BCA' (length=3)
private 'institute' => string 'CET' (length=3)
这是映射器函数。
/**
* @param MatEducation $obj - i am passing this object so that
* function dont need to create 'new' object every time.if i create
* a new object then i get the desired result.
* @param array $arr this array contain the value to be converted.
* @return MatEducation
*/
public function toMatEducation(MatEducation $obj, array $arr)
{
$obj->setEduId($arr['edu_id']);
$obj->setDegree($arr['edu_degree']);
$obj->setInstitute($arr['edu_institute']);
return $obj;
}
而对映射器函数的调用就像 -
/**return array of MatEducation Objects.*/
$arrayOfObject = array();
foreach ($result as $key=>$row) {
$arrayOfObject[$key] = $this->map->toMatEducation($education, $result[$key]);
}
return $arrayOfObject;
由于默认情况下所有传递的值都是“按值传递”,因此$education 对象不能更改,并且应该从函数返回它的副本。如果它比分配给$arrayOfObject[$key] 时仍然变化,则应生成一个新副本。所以我的问题是为什么$arrayOfObject 的所有索引都指向同一个对象。?
编辑这是我现在得到的数组。
array (size=2)
0 =>
object(MatEducation)[11]
private 'id' => int 1
private 'eduId' => string '4' (length=1)
private 'degree' => string 'BCA' (length=3)
private 'institute' => string 'CET' (length=3)
1 =>
object(MatEducation)[11]
private 'id' => int 1
private 'eduId' => string '4' (length=1)
private 'degree' => string 'BCA' (length=3)
private 'institute' => string 'CET' (length=3)
【问题讨论】:
标签: php