dimanche 4 septembre 2016

Parsing changing JSON from API - what design pattern to use - PHP

I am getting article/articles from an API. The JSON object varies, some articles have properties that some other do not have.

I need to iterate through the items and manipulate the properties, if they are set.

What is the best way to tackle this?

Actually for now I do something that I find very ugly...

foreach ($items as $key => $item) {
  if(isset($item->title)){
     $parsed[$key]['title'] = $this->formatTitle($item->title);
  }
  if(isset($item->salutation)){$parsed[$key]['salutation'] = $item->salutation;}
  if(isset($item->eventDate) && isset($item->enventEndDate)){
     $parsed[$key]['eventDates'] = $this->ersDate($item->eventDate, $item->eventEndDate);
     $parsed[$key]['startDateTimestamp'] = $this->toTimestamp($item->eventDate);
     } elseif(isset($item->eventDate) && !isset($item->enventEndDate)){
     $parsed[$key]['eventDates'] = $this->ersDate($item->eventDate);
     $parsed[$key]['startDateTimestamp'] = $this->toTimestamp($item->eventDate);
      }

//... code continues ...

Aucun commentaire:

Enregistrer un commentaire