array_reduce的使用

发布时间 2023-07-02 11:00:59作者: 小刘的早餐店

当使用 array_reduce 函数编写博客时,可以使用它来对一个数组进行迭代并将每个元素归约(规约)成一个单一的值。下面是一个简单的示例来说明它的用法:

// 假设我们有一个博客数组,每个博客都有一个评论数

$blogs = [
    ['title' => '博客1', 'comments' => 10],
    ['title' => '博客2', 'comments' => 5],
    ['title' => '博客3', 'comments' => 8],
];

// 使用 array_reduce 函数计算所有博客的评论总数
$totalComments = array_reduce($blogs, function ($carry, $blog) {
    return $carry + $blog['comments'];
}, 0);

// 输出评论总数
echo "所有博客的评论总数:" . $totalComments;

上述示例中,我们使用了 array_reduce 函数对 $blogs 数组中的每个博客的评论数进行求和。初始值为 0(作为第三个参数传递给 array_reduce),然后我们在每次迭代中将评论数累加到 $carry 中并返回。

最终,我们得到了所有博客的评论总数并将其输出。