This note is used to sort out the actual application scenarios of Collection in Laravel.

sum

Requirement: iterate through the $orders array to find the sum of prices.

<? PHP // package require __DIR__. '/vendor/autoload.php'; $orders = [[ 'id' => 1, 'user_id' => 1, 'number' => '13908080808', 'status' => 0, 'fee' => 10, 'discount' => 44, 'order_products'=> [ [' order_id = > 1, 'product_id = > 1, the' param '= >' 6 'and' price '= > 555.00, the' product '= > [' id' = > 1, 'name' = > 'cake name', 'images' = > []]]. [' order_id = > 1, 'product_id = > 1, the' param '= >' 7 "', 'price' = > 333.00, 'product' = > [' id '= > 1,' name '= >' cake name ', 'images' = > []]],]]].
  1. Using traditional foreach traversal:
$sum = 0;
foreach ($orders as $order) {
    foreach ($order['order_products'] as $item) {
        $sum += $item['price'];
    }
}
echo $sum;
  1. Use the map, flatten, sum of the collection:
$sum = collect($orders)->map(function($order){
    return $order['order_products'];
})->flatten(1)->map(function($order){
    return $order['price'];
})->sum();

echo $sum;

Map: Iterates through the collection, returning a new collection. Flatten: Converts a multidimensional array to one-dimensional. Sum: Returns the sum of an array.

  1. Using FlatMap, Pluck, Sum for the collection:
$sum = collect($orders)->flatMap(function($order){
    return $order['order_products'];
})->pluck('price')->sum();
echo $sum;

FlatMap: Similar to Map, except that the FlatMap can use the returned new collection directly.

  1. Using the FlatMap of the collection, Sum:
$sum = collect($orders)->flatMap(function($order){
    return $order['order_products'];
})->sum('price');

SUM: You can accept a column name as an argument to sum.

Formatted data

Requirement: Format the array with the following structure into the following new array.

$gates = ['BaiYun_A_A17', 'BeiJing_J7', 'ShuangLiu_K203', 'HongQiao_A157', 'A2', 'BaiYun_B_B230']; / / new array $boards = [' A17 ', 'J7', 'K203', 'A157', 'A2', 'B230];
  1. Using foreach to traverse:
$res = [];
foreach($gates as $key => $gate) {
    if(strpos($gate, '_') === false) {
        $res[$key] = $gate;
    }else{
        $offset = strrpos($gate, '_') + 1;
        $res[$key] = mb_substr($gate , $offset);
    }
}
var_dump($res);
  1. / / explode; / / end;
$res = collect($gates)->map(function($gate) {
    $parts = explode('_', $gate);
    return end($parts);
});
  1. Use map, explode, last, toArray on the set:
$res = collect($gates)->map(function($gate) {
    return collect(explode('_', $gate))->last();
})->toArray();

Last: Returns the last element in an array

Statistics making Event

First, get the personal event JSON through this link.

A PushEvent is worth 5 points, a CreateEvent is worth 4 points, a IssueCommentEvent is worth 3 points, a IssueCommentEvent is worth 2 points, and any other type of event is worth 1 point. Calculates the sum of the time scores for the current user.

$opts = [
        'http' => [
                'method' => 'GET',
                'header' => [
                        'User-Agent: PHP'
                ]
        ]
];
$context = stream_context_create($opts);
$events = json_decode(file_get_contents('http://api.github.com/users/0xAiKang/events', false, $context), true);
  1. Traditional Foreach:
$eventTypes = []; // Event type $score = 0; $eventTypes[] = $event['type']; $event['type']; } foreach($eventTypes as $eventType) { switch ($eventType) { case 'PushEvent': $score += 5; break; case 'CreateEvent': $score += 4; break; case 'IssueEvent': $score += 3; break; case 'IssueCommentEvent': $score += 2; break; default: $score += 1; break; }}
  1. Use the map, pluck, sum methods of the collection:
$score = $events->pluck('type')->map(function($eventType) {
   switch ($eventType) {
      case 'PushEvent':
      return 5;
      case 'CreateEvent':
      return 4;
      case 'IssueEvent':
      return 3;
      case 'IssueCommentEvent':
      return 2;
      default:
      return 1;
  }
})->sum();

Using chained programming with collections is a good way to solve the multiple traversal problem above.

  1. Use the map, pluck, and get methods in the collection:
$score = $events->pluck('type')->map(function($eventType) { return collect([ 'PushEvent'=> 5, 'CreateEvent'=> 4, 'IssueEvent'=> 3, 'IssueCommentEvent'=> 2 ])->get($eventType, 1); // default = 1})->sum();
  1. Try to encapsulate this requirement into a class:
class GithubScore { private $events; private function __construct($events){ $this->events = $events; } public static function score($events) { return (new static($events))->scoreEvents(); } private function scoreEvents() { return $this->events->pluck('type')->map(function($eventType){ return $this->lookupEventScore($eventType, 1); })->sum(); } public function lookupEventScore($eventType, $default_value) { return collect([ 'PushEvent'=> 5, 'CreateEvent'=> 4, 'IssueEvent'=> 3, 'IssueCommentEvent'=> 2 ])->get($eventType, $default_value); Var_dump (GithubScore::score($events));

Formatted data

Requirement: Format the following data into a new structure.

$messages = [ 'Should be working now for all Providers.', 'If you see one where spaces are in the title let me know.', 'But there should not have blank in the key of config or .env file.' ]; // Formatted result - Should be working now for all Providers. \n - If you see one where Spaces are in the title let me know. \n  - But there should not have blank in the key of config or .env file.
  1. The traditional foreach method:
$comment = '- ' . array_shift($messages);
foreach ($messages as $message) {
    $comment .= "\n -  ${message}";
}
var_dump($comment);
  1. Use the map, implode method of the collection:
$comment = collect($messages)->map(function($message){
    return '- ' . $message;
})->implode("\n");
var_dump($comment);

Multiple arrays are differentiated

Demand: the two groups of data respectively represent last year’s revenue and this year’s revenue, seeking the monthly profit and loss situation.

$lastYear = [6345.75, 9839.45, 7134.60, 9479.50, 9928.0, 8652.00, 7658.40, 10245.40, 7889.40, 3892.40, 3638.40, $lastYear = [6345.75, 9839.45, 7134.60, 9479.50, 9928.0, 8652.00, 7658.40, 10245.40, 7889.40, 3892.40, 3638.40, 2339.40]; $thisYear = [6145.75, 6895.00, 3434.00, 9349350, 9478.60, 7652.80, 4758.40, 10945.40, 3689.40, 8992.40, 7588.40, 2239.40];
  1. The traditional foreach method:
$profit = [];
foreach($thisYear as $key => $monthly){
    $profit[$key] = $monthly - $lastYear[$key];
}
var_dump($profit);
  1. Use the Zip, First, Last of the collection:
$profit = collect($thisYear)->zip($lastYear)->map(function($monthly){
    return $monthly->first() - $monthly->last();
});

Zip: Merges the value of the given array with the value of the original collection at the corresponding index.

Create a lookup array

Requirement: Format the following array into the following result:

$employees = [ [ 'name' => 'example', 'email' => '[email protected]', 'company' => 'example Inc.' ], [ 'name' => 'Lucy', 'email' => '[email protected]', 'company' => 'ibm Inc.' ], [ 'name' => 'Taylor', 'email' => '[email protected]', 'company'=>'Laravel Inc.' ] ]; $lookup = ['example' => '[email protected]', 'Lucy' => 'let ', $lookup = ['example' => '[email protected]', 'Lucy' =>' let ', 'Taylor'=> '[email protected]' ];
  1. The traditional foreach method:
$emails = [];
foreach ($employees as $key => $value) {
    $emails[$value['name']] = $value['email'];
}
  1. Reduce method using the set:
$emails = collect($employees)->reduce(function($emailLookup, $employee){
    $emailLookup[$employee['name']] = $employee['email'];
    return $emailLookup;
},[]);

Reduce: Pass the results of each iteration to the next iteration until the set is reduced to a single value.

  1. Use the pluck method of the collection:
$emails = collect($employees)->pluck('name', 'email');

Refer to the link

  • Use of Collection in real-world development