【发布时间】:2018-04-13 17:28:36
【问题描述】:
如果我有这样的数组
$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 hydration 的函数,希望得到一些线索,但没有找到任何类似于我想做的事情
【问题讨论】:
-
基本上你想将一个对象值映射到另一个对象值?你的最终目标是什么?因为您可能想到了错误的解决方案?
-
也许:
json_decode(json_encode($arr));? -
@Niels 我想对所有项目数据使用相同的模型,所以当我传递对象时,我没有 100 个转换器函数,但输出不同
-
@smoqadam 已经尝试过 .. 您必须首先在 json 中实际添加数据 .. 但我想要的是放置对数据进行编码的模式 .. 有点像 sprintf 但对于对象和数组