대충이라도 하자

fetch the total data in the easier way 본문

꼬꼬마 개발자 노트/PHP

fetch the total data in the easier way

Sueeeeee
반응형

Situation : 

1. fetch the data of tags

2. In data of tags, there are many columns

3. Gonna insert the data as a table type, and bring it as json type

Ex)

 "tags": {
      "columns": [
        "url",
        "adtype",
        "sitecode",
        "category",
        "type",
        "channel",
        "product",
        "phase",
        "campaign",
        "media",
        "creative",
        "segment"
      ],
      "rows": [
        [
          "www.samsung.com/sec",
          "display",
          "sec",
          "paid",
          "display",
          "facebook",
          "feed",
          "launch",
          "sec.bespoke.2021",
          "image",
          "i20210101",
          "re-1234"
        ],
        [
          "www.samsung.com/sec",
          "display",
          "sec",
          "paid",
          "display",
          "youtube",
          "trueview",
          "ecommerce",
          "sec.bespoke.2021",
          "video",
          "v20210101",
          "re-1234"
        ],

 

 

Original Code

$tags = array_map(function ($tag) {
            //imo. except channel and campaign
            //everything seems not neccessary
            return [
                'url' => tag[0] ??null,
                'adtype'  => tag[1] ?? null,
                'sitecode' => tag[2] ?? null,
                'category' => tag[3] ?? null,
                'type' => tag[4] ?? null,
                'channel' => tag[5],
                'product' => tag[6] ?? null,
                'phase' => tag[7] ?? null,
                'campaign' => tag[8],
                'media' => tag[9] ?? null,
                'creative' => tag[10] ?? null,
                'segment' => tag[11] ?? null,
            ];
        }, $cmp->data->tags->rows);

 

Changed Code

$columns = $tagData->columns;
        $rows = $tagData->rows;
        array_map(function($row) use($columns) {
            $el = [];
            foreach($columns as $ci=>$colname) {
                $el[$colname] = $row[$ci] ?? null;
            }
        }, $rows);

 

 

Same when updating and saving data

$cmp->data->tags = $body;
        $cmp->save();
        return $this->response->json($cmp->data->tags);

=> Without thinking of columns and rows, just save as it is.

No need to think about finding tags to be updated.

반응형
Comments