【问题标题】:Creating an Associate array from Laravel db从 Laravel db 创建关联数组
【发布时间】:2020-12-04 00:34:01
【问题描述】:

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

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"
}
}

【问题讨论】:

  • 请证明已经尝试过的代码
  • 我提供了 2 个代码我试过但没有任何效果

标签: php arrays laravel api associate


【解决方案1】:

也试试这个

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

【讨论】:

  • 返回相同的内容,开头有一个额外的 []
  • 你需要的 JSON 格式是什么? [ { "codes":[], "names":[] } ] 还是其他?
  • 我需要一个索引多维数组,所以 [0]=>{"id": 1, "description": "test", "price": "9.00", "currency": "EUR ”,“状态”:“打开”,“deleted_at”:空,“created_at”:“2020-08-10T09:50:52.000000Z”,“updated_at”:“2020-08-10T09:50:52.000000Z”}
【解决方案2】:

试试这个

public function index()
{
    $payments = Payment::get()->toArray();

    return $payments;
}

【讨论】:

  • 不幸的是返回相同的结果
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-04
  • 2014-08-17
  • 2014-06-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多