从 Laravel db 创建关联数组

目前我正在构建一个带有 flutter 的应用程序,但我的 Laravel api 控制器没有返回适当的多维数组。我想要 { [0]=> 数组,[1]=> 数组等}。如果有人知道解决此问题的方法,我们将不胜感激


public function index()

    {

        $payments = Payment::all();


        return $payments;

    }

它返回这个:


[

    {

        "id": 1,

        "description": "test",

        "price": "9.00",

        "currency": "EUR",

        "status": "open",

        "deleted_at": null,

        "created_at": "2020-08-10T09:50:52.000000Z",

        "updated_at": "2020-08-10T09:50:52.000000Z"

    },

    {

        "id": 2,

        "description": "test",

        "price": "3.00",

        "currency": "USD",

        "status": "open",

        "deleted_at": null,

        "created_at": "2020-08-13T19:06:23.000000Z",

        "updated_at": "2020-08-13T19:06:23.000000Z"

    }

]

我尝试了很多,这让我最接近,但后来我得到了 1:{ARRAY}


我尝试过的代码:


public function index()

    {

        $data = [];

        $payments = Payment::all();

        $id=1;

        foreach($payments as $payment){

            array_push($data,[$id=>$payment]);

            $id++;

        }

        return $data;

    }


结果:


[

    {

        "1": {

            "id": 1,

            "description": "test",

            "price": "9.00",

            "currency": "EUR",

            "status": "open",

            "deleted_at": null,

            "created_at": "2020-08-10T09:50:52.000000Z",

            "updated_at": "2020-08-10T09:50:52.000000Z"

        }

    },

    {

        "2": {

            "id": 2,

            "description": "test",

            "price": "3.00",

            "currency": "USD",

            "status": "open",

            "deleted_at": null,

            "created_at": "2020-08-13T19:06:23.000000Z",

            "updated_at": "2020-08-13T19:06:23.000000Z"

        }

    }

    

]

我想拥有:


{

1:{

   "message":"test",

   "price":"9"

   "currency":"EUR"

  },

2:{

   "message":"test",

   "price":"9"

   "currency":"EUR"

}


扬帆大鱼
浏览 90回答 2
2回答

慕勒3428872

也试试这个  public function index(){    $payments = Payment::all();    return response()->json([$payments]); }

BIG阳

也试试这个  public function index(){    $payments = Payment::all();    return response()->json([$payments]); }
打开App,查看更多内容
随时随地看视频慕课网APP