Quantcast
Channel: 配列タグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 813

データを配列ではなく、オブジェクトの形で保存できるstdClassを使いましょう !!

$
0
0

データを配列ではなく、オブジェクトの形で保存できるstdClassを使いましょう !!

バックエンドでAPIを作成しJson形式でフロントに渡す実装をする時、
ローカル環境とテスト環境で挙動が違ってハマった点を記載します。

データを配列でJson形式に渡した時

        foreach ($payslipList as $key=>$value) {
            //合計金額の計算
            $total =$value->amount_tax  -$rental_amount_tax;

            //合計金額がマイナス時は一覧に出力しない
            if($total > 0){
                //API
                $payslipData[$key]['year'] = $year;
                $payslipData[$key]['month'] = $month;
                $payslipData[$key]['text'] = $year . '年'. $month .'月度 御支払通知書'
            }
        }

配列dataのキーが連続でない下記のAPIの場合、フロントではオブジェクトとして受け取れるが、

{
   “status”: 200,
   “response_time”: 1.8469810485839844,
   “message”: “処理を完了しました。“,
   “data”: {
       “0": {
           “year”: “2019",
           “month”: “11",
           “text”: “2019年11月度 御支払通知書”
       },
       “2”: {
           “year”: “2019”,
           “month”: “09”,
           “text”: “2019年09月度 御支払通知書”
       }
   }
}

しかし、配列dataのキーが連続である下記のAPIの場合、フロントでは配列として受け取れるらしい

{
    "status": 200,
    "response_time": 2.6169888973236084,
    "message": "処理を完了しました。",
    "data": [
        {
            "year": "2019",
            "month": "11",
            "text": "2019年11月度 御支払通知書"
        },
        {
            "year": "2019",
            "month": "09",
            "text": "2019年09月度 御支払通知書"
        }
    ]
}

stdClass利用してデータを配列に渡した時

        foreach ($payslipList as $key=>$value) {
            //合計金額の計算
            $total =$value->amount_tax  -$rental_amount_tax;

            //合計金額がマイナス時は一覧に出力しない
            if($total > 0){
                //API
                $payslipJson = new \stdClass();
                $payslipJson->year = $year;
                $payslipJson->month = $month;
                $payslipJson->text = $year . '年'. $month .'月度 御支払通知書';
                $payslipData[] = $payslipJson;
            }
        }

配列dataのキーがいつも連続なので、フロントではいつも配列として受け取れるようになる。

{
    "status": 200,
    "response_time": 2.8132009506225586,
    "message": "処理を完了しました。",
    "data": [
        {
            "year": "2019",
            "month": "11",
            "text": "2019年11月度 御支払通知書"
        },
        {
            "year": "2019",
            "month": "09",
            "text": "2019年09月度 御支払通知書"
        }
    ]
}

参考サイト

http://phpspot.net/php/pgPHP%E6%A8%99%E6%BA%96%E3%82%AF%E3%83%A9%E3%82%B9%E3%81%AEstdClass%E3%81%AB%E3%81%A4%E3%81%84%E3%81%A6.html


Viewing all articles
Browse latest Browse all 813

Trending Articles