Laravel - 使json - 添加到可变的新对象

时间:2016-04-19 23:23:23

标签: php json laravel eloquent php-carbon

我有这个功能来获取maxoffers表中的所有最大优惠:

public function maxoffers($id)
    {

        $offers = Maxoffer::where('article_id', $id)->latest()->get(['id', 'price', 'start', 'user_id']);

        return $offers;
    }

我得到了这个:

[{"id":121,"price":67,"start":"Sat, 23 Apr 2016 00:00:00 +0000","user_id":8},{"id":114,"price":45,"start":"Sun, 08 May 2016 00:00:00 +0000","user_id":9},{"id":113,"price":53,"start":"Sun, 24 Apr 2016 00:00:00 +0000","user_id":8},{"id":111,"price":55,"start":"Wed, 01 Jun 2016 00:00:00 +0000","user_id":11},{"id":110,"price":53,"start":"Fri, 03 Jun 2016 00:00:00 +0000","user_id":8},{"id":107,"price":53,"start":"Wed, 03 Aug 2016 00:00:00 +0000","user_id":8},{"id":106,"price":53,"start":"Mon, 01 Aug 2016 00:00:00 +0000","user_id":8},{"id":105,"price":53,"start":"Tue, 16 Aug 2016 00:00:00 +0000","user_id":8},{"id":104,"price":55,"start":"Thu, 21 Apr 2016 00:00:00 +0000","user_id":11},{"id":101,"price":57,"start":"Wed, 17 Aug 2016 00:00:00 +0000","user_id":8}]

现在我有: $ start ='Sun,2016年4月3日00:00:00'; $ end ='星期六,2016年9月23日00:00:00';

我如何能够从$开始日期到$结束日期一天一天地进行$ offer,如果当天没有日期添加到$ offer中,则提供包含数据的新对象:

{"title":,"price":100,"start":"DATE_WHICH_NOT_EXCIST INTO_OFFERS","user_id":8}

那么我怎样才能通过$ offer,如果从$ start到$ end之间没有一些日期,那么将新对象添加到json?

1 个答案:

答案 0 :(得分:1)

我还没有执行以下代码,但你想要的是这样的。

试试这个:

 public function maxoffers($id)
    {

        $start_date = ;
        $end_date = ;

        $offers = Maxoffer::where('article_id', $id)
                            ->where('start', '>=', $start_date)
                            ->where('start', '<=', $end_date)
                            ->get(['id', 'price', 'start', 'user_id']);

        $start_date = 'Sun, 03 Apr 2016 00:00:00';

        $end_date = 'Sat, 23 Sep 2016 00:00:00';

        while (strtotime($start_date) <= strtotime($end_date)) {

            $start_date = date ("Y-m-d", strtotime("+1 day", strtotime($start_date)));

            $count = 0;

            foreach($offers as $offer) {
                if(strtotime($offer->start) == strtotime($start_date)) {
                    $count++;
                }
            }

            if($count == 0) {
                Maxoffer::create(['title' => null, 'price' => '100', 'start' => $start_date, 'user_id' => 8 ]);   
            }

        }

        // do some code to update $offers variable before you return it

        return $offers;
    }