【问题标题】:php object format from string来自字符串的 php 对象格式
【发布时间】: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 但对于对象和数组

标签: php arrays stdclass


【解决方案1】:

所以你需要这样的东西吗?希望这能让你朝着正确的方向前进。现在您可以创建一个传递模型名称和数据行的函数。从数据生成任何模型。

$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);

注意:此代码未经测试

【讨论】:

  • 很抱歉,您错过了重点.. 重点是您可以更改对象内的返回变量“对象将遵循所需的格式,而不是硬编码设计”
【解决方案2】:

经过多次环顾后,我找不到像我问的那样的东西,所以我自己做了一个

Github - Objectron

它的功能有限,可能没有经过很好的测试,也没有单元测试,但它做得很好

你可以给它传递一个数组或对象,然后告诉它返回你想要的设计对象。

'%id% = %name%'
'Student Name = %student_name%' 

我会尽量更新和添加更多内容

【讨论】:

    猜你喜欢
    • 2020-01-31
    • 2013-04-21
    • 2017-09-03
    • 2013-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-21
    相关资源
    最近更新 更多