php - 将 api 输出从对象更改为数组 laravel

标签 php mysql laravel

我有一个 API,它返回一个对象作为结果中的包装数据,如下所示:

{
data: {
totalSalesPrice: 0,
totalDiscount: 0,
finalPrice: 0
}
}

但我希望它是一个如下所示的数组:

{
data: [
totalSalesPrice: 0,
totalDiscount: 0,
finalPrice: 0
]
}

或者甚至像下面这样:

{
data: [ 
{
totalSalesPrice: 0,
totalDiscount: 0,
finalPrice: 0
}
]
}

我怎样才能实现这个目标?这是我的方法:

 public function getPriceDetails($bookingId)
    {
        $booking = AccommodationBooking::where('id', $bookingId)->with('accommodationRoom')->first();
        $roomsOfBook = DB::table('accommodation_booking_accommodation_room')->where('accommodation_booking_id', $bookingId)->get();

        $result = [];
        foreach ($roomsOfBook as $room) {
            $roomPricingHistory = RoomPricingHistory::where('accommodation_room_id', $room->accommodation_room_id)
                ->whereDate('from_date', '<=', $booking->from_date)
                ->whereDate('to_date', '>=', $booking->to_date)
                ->orderBy('created_at', 'desc')
                ->first();
            $result[] = $roomPricingHistory;
        }

        $totalSalesPrice = collect($result)->sum('sales_price');
        $totalDiscount = 0;
        $finalPrice = $totalSalesPrice;

        $result['totalSalesPrice'] = $totalSalesPrice;
        $result['totalDiscount'] = $totalDiscount;
        $result['finalPrice'] = $finalPrice;
        return new RoomDetailResource($result);
    }

最佳答案

我想看看您如何返回 RoomDetailResource 中的数据。 理想情况下,要实现第二个结果,您只需返回 JSON 响应即可 您的 RoomDetailResource 的方式:

 return response()->json([
        'data' => your_result
    ], status_code);

假设这是我们要输出的结果:

$result['totalSalesPrice'] = $totalSalesPrice;
$result['totalDiscount'] = $totalDiscount;
$result['finalPrice'] = $finalPrice;

在这种情况下,您将得到输出:

{
data: [ 
  {
    totalSalesPrice: 0,
    totalDiscount: 0,
    finalPrice: 0
  }
]
}

这是我的代码示例:

这是我的服务并返回一个集合。 enter image description here

这是我的 Controller 。 enter image description here

这是我的 postman 结果。 enter image description here

关于php - 将 api 输出从对象更改为数组 laravel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58890748/

相关文章:

php - laravel 迁移 :rollback wrong

jquery - Uncaught ReferenceError : data is not defined in doing a math calculation in jQuery

php - 将 PHP 数组值与字符串的一部分进行比较

php - 我需要将 mysql 查询转换为 CakePHP 条件

php - getmypid() 和 posix_getpid() 之间的区别

mysql - Python - MySql.Connector UPDATE 语句不起作用

mysql - 运算符喜欢,字段类型时间戳和西里尔字母? MySQL错误?

java - 是否有任何 JDBC 驱动程序支持 LOAD DATA INFILE sql 命令?

php - 通过 php api 从数据库获取图像 url 时获取空白 json 响应

php - 在 Laravel Controller 的每个函数中传递用户信息