2017-05-08 17 views
0

我有以下代码:如何在变压器Laravel中构建多个阵列?

public function transform($obj) 
{ 
    return [ 
     'id'  => (int) $obj->id, 
     'name' => $obj->name, 
     "prototype" => $obj->_prototypes()->get() 
    ]; 
} 

哪里$obj->_prototypes()->get()是收集与场(id, name)

如何格式化新的数组一样为:

'name' => 'name' => $obj->name, 
"prototype" => [ 
    ["id": 1, "name" : "ok"], 
    ["id": 2, "name" : "ok 2"], 
] 

所以,我需要遍历$obj->_prototypes()->get()变压器对象内。

所以,我有嵌套的对象(关系)。现在我需要使用循环,即获取嵌套对象并再次将它们组合到一个输出对象。

回答

0

绝对看一看分形的变压器。有非常好的特性,包括你的:http://fractal.thephpleague.com/transformers/

class MyTransformer extends TransformerAbstract 
{ 
    public $defaultIncludes = ['prototype']; 

    public function transform($obj) 
    { 
     return [ 
      'id' => (int) $obj->id, 
      'name' => $obj->name 
     ] 
    } 

    public function includePrototype($obj) 
    { 
     return $this->collection($obj->_prototypes()->get(), new PrototypeTransformer); 
    } 
} 
+0

是的,但是当我尝试变换@Gagamerov我更新我的代码片段答案转化对象 – Gagamerov

+0

内部对象这是行不通的。这是你在找什么? –