PHP code example of php-brasil / collection
1. Go to this page and download the library: Download php-brasil/collection library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
php-brasil / collection example snippets
use PhpBrasil\Collection\Pack;
$array = Pack::create([['name' => 'PHP']]);
foreach ($array as $item) {
echo 'item ~> ', $item, ';', PHP_EOL;
}
# item ~> PHP;
use PhpBrasil\Collection\Pack;
$pack = Pack::create([
['id' => 3, 'amount' => 60],
['id' => 2, 'amount' => 20],
['id' => 3, 'amount' => 125],
]);
$reduced = $pack->reduce(function($accumulator, $value) {
$id = prop($value, 'id');
$amount = prop($value, 'amount');
if (!isset($accumulator[$id])) {
$accumulator[$id] = [
'id' => $id,
'amount' => 0,
];
}
$accumulator[$id]['amount'] = $accumulator[$id]['amount'] + $amount;
return $accumulator;
}, []);
echo stringify($reduced);
use function PhpBrasil\Collection\pack;
$array = pack([['name' => 'PHP']]);
echo 'with-pluck ~> ', $array->pluck('name'), ';', PHP_EOL;
echo 'original ~> ', $array, ';', PHP_EOL;
# [
# "PHP"
# ];
# [
# [
# "name" => "PHP"
# ]
# ];
echo Pack::create(['A', '', 'C'])->filter();
# [
# 0 => "A",
# 2 => "C"
# ];
$statement = $pdo->prepare("SELECT id, name FROM users WHERE name = ?");
$statement->execute([get('name')]);
$users = Fetch::create($statement->fetchAll(PDO::FETCH_ASSOC), User::class);
$first = $users->current();
echo get_class($first);
echo $first->id;
# User
# 1