如何在laravel中将数组的值推入自己的对象项中 [英] how to push values of an array into thier own item of object in laravel

查看:47
本文介绍了如何在laravel中将数组的值推入自己的对象项中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要返回的对象,如下所示:(dd结果)

 集合{#1421▼#项:数组:2 [▼3943 =>集合{#1419▼#项:数组:2 [▼0 =>RoomPricingHistory {#923▼#fillable:array:19 [▶]#connection:"mysql"#table:" room_pricing_histories"#primaryKey:"id"#keyType:"int";+递增:是#和: []#withCount:[]#每页:15+存在:真实+ wasRecentlyCreated:否#attributes:array:26 [▶]#original:数组:26 [▼"id"=>4132" accommodation_room_id"=>3943"net_price"=>空值"board_price"=>空值"foreign_board_price"=>空值"sales_price"=>4200000" extra_bed_price"=>空值"half_charge_price"=>空值"half_board_price"=>空值"full_board_price"=>空值"foreign_net_price"=>空值"foreign_sales_price"=>空值"foreign_extra_bed_price"=>空值"foreign_half_charge_price"=>空值"foreign_half_board_price"=>空值"foreign_full_board_price"=>空值"operator_id";=>11"commission_percent"=>空值"foreign_commission_percent"=>空值"discount_percent"=>10.0"foreign_discount_percent"=>空值"from_date"=>" 2019-05-25 00:00:00""to_date"=>" 2029-08-30 23:59:59""is_deleted"=>0"created_at"=>" 2019-05-25 13:30:00""updated_at"=>" 2019-05-25 13:30:00"]#变化: []#casts:[]#日期: []#dateFormat:null#appends:[]#dispatches事件:[]#observables:[]#relations:数组:1 [▶]#touches:[]+时间戳:真实#隐藏:[]#可见的: []#guarded:数组:1 [▶]#enableLoggingModelsEvents:正确#oldAttributes:[]}1 =>RoomPricingHistory {#1042▶}]}3944 =>集合{#1420▶}]} 

我有一些映射数据,如下所示:

 集合{#1422▼#项:数组:2 [▼3943 =>84000003944 =>400]} 

现在我要做的是返回映射的数据,该数据是根据它们具有的id的价格总和,因此每个项目的结果中都包含价格总和,如下所示:

  {//房间价格记录编号:4132room_id:3943价格总和:8400000},{//房间价格记录编号:4133room_id:3944价格总和:600} 

注意:我当前正在使用资源,但是我不知道如何将数据推送到自己的对象中,例如,在这种情况下,它们具有相同的id或某些东西.

UPDATE:

这是我的方法:

  $ from_date = $ request-> get('from_date');$ to_date = $ request-> get('to_date');$ acc_id = $ request-> get('acc_id');$ room_price = [];$ period = CarbonPeriod :: create($ from_date,$ to_date);$ dates = $ period-> toArray();$ room_ids = AccommodationRoom :: where('accommodation_id',$ acc_id)-> pluck('id')-> toArray();for($ f = 0; $ f< count($ room_ids); $ f ++){for($ i = 0; $ i< count($ dates); $ i ++){/*********************************************循环显示用户给定的房间数**********************************************/$ room_price [] = RoomPricingHistory :: with('accommodationRoom','accommodationRoom.roomCapacityHistoryLast')->其中('accommodation_room_id',$ room_ids [$ f])-> whereDate('from_date','< =',$ dates [$ i])-> whereDate('to_date','> =',$ dates [$ i])-> get()-> sortByDesc('created_at')-> take(1);}}$ room =收集($ room_price);$ room_collection = $ room-> flatten();$ sums = $ detailed-> mapWithKeys(function($ group,$ key){返回[$ key =>$ group-> sum('sales_price')];});返回RoomDetailResource :: collection($ room_collection); 

解决方案

基于上一个问题,我们研究了如何获取各组的总和,我们可以在此基础上进行扩展,以包括您想要的任何其他数据并使用<代码>地图:

  $ new = $ detailed-> map(function($ group,$ key){返回(对象)['id'=>$ group-> first()-> id,'room_id'=>$键,'sum_of_prices'=>$ group-> sum('sales_price'),];})-> values(); 

我们在最后抛出 values 调用以重置密钥,因此JSON输出将是一个数组而不是对象,并且您的示例输出似乎未使用密钥.如果您仍然希望这些以"room_id"作为键的对象,请不要调用 values .

尽管我不确定您实际上要做什么,因为您拥有的任何API资源都需要特定的数据.您似乎想将任意数据混合到Eloquent集合中.

i have an object to return like below : (the dd result)

Collection {#1421 ▼
  #items: array:2 [▼
    3943 => Collection {#1419 ▼
      #items: array:2 [▼
        0 => RoomPricingHistory {#923 ▼
          #fillable: array:19 [▶]
          #connection: "mysql"
          #table: "room_pricing_histories"
          #primaryKey: "id"
          #keyType: "int"
          +incrementing: true
          #with: []
          #withCount: []
          #perPage: 15
          +exists: true
          +wasRecentlyCreated: false
          #attributes: array:26 [▶]
          #original: array:26 [▼
            "id" => 4132
            "accommodation_room_id" => 3943
            "net_price" => null
            "board_price" => null
            "foreign_board_price" => null
            "sales_price" => 4200000
            "extra_bed_price" => null
            "half_charge_price" => null
            "half_board_price" => null
            "full_board_price" => null
            "foreign_net_price" => null
            "foreign_sales_price" => null
            "foreign_extra_bed_price" => null
            "foreign_half_charge_price" => null
            "foreign_half_board_price" => null
            "foreign_full_board_price" => null
            "operator_id" => 11
            "commission_percent" => null
            "foreign_commission_percent" => null
            "discount_percent" => 10.0
            "foreign_discount_percent" => null
            "from_date" => "2019-05-25 00:00:00"
            "to_date" => "2029-08-30 23:59:59"
            "is_deleted" => 0
            "created_at" => "2019-05-25 13:30:00"
            "updated_at" => "2019-05-25 13:30:00"
          ]
          #changes: []
          #casts: []
          #dates: []
          #dateFormat: null
          #appends: []
          #dispatchesEvents: []
          #observables: []
          #relations: array:1 [▶]
          #touches: []
          +timestamps: true
          #hidden: []
          #visible: []
          #guarded: array:1 [▶]
          #enableLoggingModelsEvents: true
          #oldAttributes: []
        }
        1 => RoomPricingHistory {#1042 ▶}
      ]
    }
    3944 => Collection {#1420 ▶}
  ]
}

and i have some mapped data like below :

Collection {#1422 ▼
  #items: array:2 [▼
    3943 => 8400000
    3944 => 400
  ]
}

now what i want to do is to return the mapped data which is the sum of price according to the id they have so the result of each item has the sum of price in it like below :

{
//room pricing history
 id:4132
room_id:3943
sum_of_prices :8400000
},
{
//room pricing history
 id:4133
room_id:3944
sum_of_prices :600
}

note : i am currently using resource but i dont know how to push the data in thier own object for example with this condition that they have the same id or something .

UPDATE :

here is my method :

  $from_date = $request->get('from_date');
        $to_date = $request->get('to_date');
        $acc_id = $request->get('acc_id');
        $room_price = [];
        $period = CarbonPeriod::create($from_date, $to_date);
        $dates = $period->toArray();
        $room_ids = AccommodationRoom::where('accommodation_id',$acc_id)->pluck('id')->toArray();
        for ($f = 0; $f < count($room_ids); $f++) {
            for ($i = 0; $i < count($dates); $i++) {


                /****************************************
                 * Looping for the Number of Rooms User Given
                 *****************************************/
                $room_price[] = RoomPricingHistory::with('accommodationRoom', 'accommodationRoom.roomCapacityHistoryLast')
                    ->where('accommodation_room_id', $room_ids[$f])
                    ->whereDate('from_date', '<=', $dates[$i])
                    ->whereDate('to_date', '>=', $dates[$i])
                    ->get()->sortByDesc('created_at')
                    ->take(1);
            }
        }
        $room = collect($room_price);
        $room_collection= $room->flatten();
        $sums = $detailed->mapWithKeys(function ($group, $key) {
            return [$key => $group->sum('sales_price')];
        });
        return RoomDetailResource::collection($room_collection);

解决方案

Based on the previous question where we worked out how to get the sums of the groups we can expand on that to include any additional data you would like and use map instead:

$new = $detailed->map(function ($group, $key) {
    return (object) [
        'id' => $group->first()->id,
        'room_id' => $key,
        'sum_of_prices' => $group->sum('sales_price'),
    ];
})->values();

We throw the values call on the end to reset the keys so the JSON output would be an array not an object, and your example output didn't seem to use keys. If you still want these objects keyed by 'room_id' don't call values.

Though I am not sure what you are actually trying to do since any API Resource you have is expecting particular data. You seem to want to mix arbitrary data into Eloquent Collections.

这篇关于如何在laravel中将数组的值推入自己的对象项中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆