LoginSignup
0
0

More than 3 years have passed since last update.

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

Last updated at Posted at 2019-10-29

データを配列ではなく、オブジェクトの形で保存できる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月度 御支払通知書"
        }
    ]
}

参考サイト

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0