【问题标题】:Doctrine - "un-nest" json fieldsDoctrine - “un-nest” json 字段
【发布时间】:2019-10-01 20:21:24
【问题描述】:

我有一个模型字段(“数据”),它映射到一个 json MYSQL 字段,如下所示:

class Person {

    /** @Id @Column(type="integer", name="person_id") @GeneratedValue **/
    protected $id;

    /** @Column(type="json") **/
    protected $data;

    /** @Column(type="string") **/
    protected $name;

}

我可以查询和序列化 Person,但是数据字段是嵌套的:

$person = $personRepository->find(11);
echo $serializer->serialize($person, 'json');
//returns {"id": 11, "name": "Daniel", "data": {"age": 57, "city": "Omaha"} }

我想取消嵌套 data 字段,以便它内联序列化。

//returns {"id": 11, "name": "Daniel", "age": 57, "city": "Omaha"}

这可能吗?

【问题讨论】:

  • 您可以尝试为这种仅将“数据”键值数组合并到主数组并删除“数据”键的实体类型编写a custom normalizer...或者如果您还需要稍后将数据反序列化回实体,您可以查看custom encoder。我在实践中没有使用/需要这些,但理论上这些看起来可以为您的问题提供答案:)

标签: php json symfony orm doctrine


【解决方案1】:

我在这里看到了不同的解决方案,从非常脏到“好吧,没关系”

所有不是很脏的解决方案(比如字符串替换大括号和其他东西),都适用于规范化数组:

$array = $serializer->normalize($person);
/** add code, that turns $array into flattened version $flattened */
$json = $serializer->encode($flattened, 'json');

现在,使数组变平的代码是什么...例如:

// if this is done in a loop, this, $flattened should be reinitialized every iteration!!!
$flattened = []; 
array_walk_recursive($array, function($value, $key) use (&$flattened) {
    $target[$key] = $value;
});
// $flattened contains the flattened array

一个稍长的版本:

// define somewhere outside of loop
function flatten($array, $flattened = []) {
    foreach($array as $key => $value) {
        if(is_array($value)) {
            $flattened = flatten($value, $flattened);
        } else {
            $flattened[$key] = $value;
        }
    }
    return $flattened;
}

// call flatten
$flattened = flatten($array);

非常奇特的解决方案是,将所有这些集成到您的自定义编码器中,扩展 json 编码器,但我想这已经是矫枉过正了。

还请注意,这在很多情况下可能并且将会中断,因为键可以被覆盖,它不能在不迭代对象的情况下应用于对象数组,它会为嵌套对象产生可能不需要的结果等。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多