2017-05-10 22 views
0

我獲得給定形式列Symfony3串行 - 如何從網點的字符串分隔值,並在一個陣列列結合

{ 
    "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 

對於visitors_country從http請求數據和views_country,數組鍵/值由點分隔。這些斑點分隔值

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

768,16是

'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; 
    } 

} 

任何想法來解決這個問題?

+0

數據是JSON?如果是這樣,然後解碼json將返回數組,然後嘗試使用爆炸選項(點)作爲您所需的數組結構 –

回答

0

試試這個:

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

enter image description here

相關問題