Php Symfony3序列化程序-如何从点字符串中分离值并合并到一个数组列中

Php Symfony3序列化程序-如何从点字符串中分离值并合并到一个数组列中,php,symfony,symfony-2.8,symfony-3.1,symfony-3.2,Php,Symfony,Symfony 2.8,Symfony 3.1,Symfony 3.2,我以给定的形式从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.fr

我以给定的形式从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
对于访客\国家/地区和视图\国家/地区,数组键/值用点分隔。这些点分隔的值

"views_country.france": 110,
"views_country.germany": 821,
"views_country.poland": 312,
应该是

'view_country' => array(
   'france'=> 110,
   'germany'=> 821,
   'poland'=> 312,
);
我正在使用Symfony serialize组件对请求的数据进行序列化,并且在对数据进行反规范化时遇到问题

我做了这样的事

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()]);
结果:


来自http的数据是json吗?如果是这样,那么解码json将返回数组,然后尝试使用带(点)的explode选项使其成为所需的数组结构