簡體   English   中英

Symfony3序列化器-如何從點字符串中分離值並將其合並到一個數組列中

[英]Symfony3 Serializer - How to separate values from dot strings and combine in one array column

我以給定的形式從http請求中獲取數據

{
  "start_date": "2017-03-13",
  "end_date": "2017-03-19",
  "visitors_total": 2555,
  "views_total": 2553,
  "visitors_country.france": 100,
  "visitors_country.germany": 532,
  "visitors_country.poland": 32,
  "views_country.france": 110,
  "views_country.germany": 821,
  "views_country.poland": 312,
}

列的學說實體定義

"start_date" => datetime
"end_date" => datetime
"visitors_total" => int
"views_total" => int
"visitors_country" => array
"views_country => array

對於visits_country和views_country,數組鍵/值由點分隔。 這些點分隔的值

"views_country.france": 110,
"views_country.germany": 821,
"views_country.poland": 312,

應該

'view_country' => array(
   'france'=> 110,
   'germany'=> 821,
   'poland'=> 312,
);

我正在使用Symfony序列化組件對請求的數據進行序列化,並且在對數據進行非規范化時遇到問題。

我做了這樣的事情

class ArrayDotNormalizer implements DenormalizerInterface
{

    /**
     * {@inheritdoc}
     *

     */
    public function denormalize($data, $class, $format = null, array $context = array())
    {
     // Actually, this function applies to each column of requested data ,
    //but how to  separate values by dot and join them in one array and store as array json in db ?
    }

    /**
     * {@inheritdoc}
     */
    public function supportsDenormalization($data, $type, $format = null)
    {

        return strpos($data, '.') !== false;
    }

}

有解決的辦法嗎?

試試這個:

class ArrayDotNormalizer extends ObjectNormalizer
{
    /**
     * {@inheritdoc}
     */
    protected function setAttributeValue($object, $attribute, $value, $format = null, array $context = [])
    {
        if (strpos($attribute, '.') !== false) {
            list($attribute, $country) = explode('.', $attribute);
            $currentValue = (array) $this->propertyAccessor->getValue($object, $attribute);
            $value = array_replace($currentValue, [$country => $value]);
        }

        return parent::setAttributeValue($object, $attribute, $value, $format, $context);
    }
}

並在序列化程序中使用此規范化器:

 $serializer = new Serializer([new ArrayDotNormalizer()], [new JsonEncoder()]);

結果:

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM