如果我有这样的数组
$arr = [
[ 'id' => 2, 'name' => 'John', 'class' => 4, 'score' => 90],
[ 'id' => 5, 'name' => 'Smith', 'class' => 5, 'score' => 30],
[ 'id' => 7, 'name' => 'Sam', 'class' => 4, 'score' => 70],
[ 'id' => 9, 'name' => 'Robot', 'class' => 6, 'score' => 100],
];
我希望将它作为对象传递但我希望该对象像运行那样设计运行时
/**
@method SomeFunction
@param array the array to be converted
@param string the name of each property line inside the object
@param array the format for each line in the property
**/
$myobject = SomeFunction( $arr, 'id', ['Student Class'=>'%class%', 'Student Name'=>'%name%']);
$mysecondobject = SomeFunction( $arr, 'name', ['student Id'=>'%id%', 'Student Score'=>'%score%']
// $myobject : stdClass {
// 2 => stdClass { 'Student Class' = 4, 'Student Name' = 'John' },
// 5 => stdClass { 'Student Class' = 5, 'Student Name' = 'Smith' },
// 7 => stdClass { 'Student Class' = 4, 'Student Name' = 'Sam' },
// 9 => stdClass { 'Student Class' = 6, 'Student Name' = 'Robot' },
// }
// $mysecondobject : stdClass {
// 'John' => stdClass { 'student Id' = 2, 'Student Score' = 90 },
// 'Smith' => stdClass { 'student Id' = 5, 'Student Score' = 30 },
// 'Sam' => stdClass { 'student Id' = 7, 'Student Score' = 70 },
// 'Robot' => stdClass { 'student Id' = 9, 'Student Score' = 100 },
// }
关键是对象将遵循所需的格式而不是硬编码设计
我看过一些做db水合作用的功能,希望得到一些线索,但没有发现任何类似于我想做的事情
答案 0 :(得分:0)
所以你需要这样的东西?希望这能让你朝着正确的方向前进。现在,您可以创建一个传递Modelname和datarow的函数。从数据生成任何模型。
$className = "myClassName"; // Generic, pass a model name
$data = [
[ 'id' => 2, 'name' => 'John', 'class' => 4, 'score' => 90],
[ 'id' => 5, 'name' => 'Smith', 'class' => 5, 'score' => 30],
[ 'id' => 7, 'name' => 'Sam', 'class' => 4, 'score' => 70],
[ 'id' => 9, 'name' => 'Robot', 'class' => 6, 'score' => 100],
];
$output = [];
foreach($data as $row){
$obj = new $className();
foreach($row as $key => $value){
$obj->{$key} = $value;
// Or if you want to use setters
// $obj->{"set" . ucfirst($key)}($value);
}
array_push($output, $obj);
}
var_dump($output);
注意:此代码未经过测试
答案 1 :(得分:0)
它的功能有限,可能没有经过良好测试,也没有单元测试,但是它完成了正确的工作
你可以传递一个数组或对象,然后告诉它返回你想要的设计对象。
'%id% = %name%'
'Student Name = %student_name%'
我会尽可能多地更新并添加更多内容