mardi 21 février 2017

Laravel collection how to subtract between items inside the each method

I got a $collection where I have non consecutive id values. I just want to get the difference between each id by subtracting the nth element minus the nth+1 element.

Here is the code:

$result_c= $collection->each(function ($item, $key)use($next) {
            $last_item = $item->id;
            if($key==0){
                echo '<p>The first item is '.$item->id.'. Key: '.$key.'</p>';
                $difference = $next-$item->id;
                echo '<p>Difference: '.$difference.'</p><hr>';
            }

        });

For the first element, the subtract is made against the most recent id plus one. But the problem lies on the next elements, I always get difference of zero ... I don't know how to work the following around:

For example, let's say I have the following IDs:

  • 3049 (The next ID to be inserted into the database) then come the following IDs already saved inside the database:

  • 3044 (difference should be 5)

  • 3038 (difference should be 6)
  • 3006 (difference should be 32)
  • 2970 (difference should be 36)
  • ...

But with this approach I get the sum (5, 11, 43, 79, ... which it's not what I want):

$result_c= $collection->each(function ($item, $key)use($next) {
            $last_item = $item->id;
            $difference=0;
            if($key==0){                
                echo '<p>The 1st item is '.$item->id.'. Key: '.$key.'</p>';
                $difference = $next-$item->id;
                echo '<p>Difference: '.$difference.'</p><hr>';
            }
            else{
                if($last_item==$item->id){
                    $difference = $last_item-$item->id;
                    echo '<p style="color: #2a88bd">Item is '.$item->id.'. Key: '.$key.'</p>';
                    $difference = $next-$item->id;
                    echo '<p style="color: #2b542c">Difference: '.$difference.'</p><hr>';
                }
            }
        });

How do I fix that? How do I actually subtract between items inside an each() method (or is there another better like map() or something else?) in a collection?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2kKosZD
via IFTTT

Aucun commentaire:

Enregistrer un commentaire