如何对多维数组中的元素进行计数和求和?

发布于 2024-11-14 01:32:22 字数 529 浏览 2 评论 0原文

我有一个返回一些数字的数组。我想将这些数字加在一起并计算它们。

这是我到目前为止所做的:

<?php
$homepage = file_get_contents('http://graph.facebook.com/215844978437619/reviews');
$parsed = json_decode($homepage,true);
foreach ($parsed['data'] as $key => $values){
$totalRatings1 = $values['rating'] ;
}
?>

我想做的是将 $values[' rating'] 相加并计算它们。

所以: $totalRatings = sum_array($values[' rating'])$totalCount = count($values[' rating'])

但我迷失在语法。

有什么想法吗? 谢谢

i have a array that returns some numbers. and i want to add those numbers together and also count them.

here is what i have so far:

<?php
$homepage = file_get_contents('http://graph.facebook.com/215844978437619/reviews');
$parsed = json_decode($homepage,true);
foreach ($parsed['data'] as $key => $values){
$totalRatings1 = $values['rating'] ;
}
?>

what i am trying to do is to sum the $values['rating'] together and also count them.

So that: $totalRatings = sum_array($values['rating']) and $totalCount = count($values['rating'])

but i get lost in the sintax.

any ideas?
Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

提笔书几行 2024-11-21 01:32:22
<?php
$homepage = file_get_contents('http://graph.facebook.com/215844978437619/reviews');
$parsed = json_decode($homepage,true);

$totalRatings = 0;
$totalRated = 0;

foreach ($parsed['data'] as $key => $values){
   $totalRatings += (int) $values['rating'];
   $totalRated++;
}
?>

$totalRatings 将具有所有评级的汇总总和,$totalRated 将是有多少评级的计数。

<?php
$homepage = file_get_contents('http://graph.facebook.com/215844978437619/reviews');
$parsed = json_decode($homepage,true);

$totalRatings = 0;
$totalRated = 0;

foreach ($parsed['data'] as $key => $values){
   $totalRatings += (int) $values['rating'];
   $totalRated++;
}
?>

$totalRatings will have the aggregated sum of all ratings, $totalRated will be the count of how many ratings there are.

九命猫 2024-11-21 01:32:22

只需声明两个变量,然后在每次迭代时递增它们:

<?php
$homepage = file_get_contents('http://graph.facebook.com/215844978437619/reviews');
$parsed = json_decode($homepage,true);

$totalRating = 0;
$totalItems = 0;
foreach ($parsed['data'] as $key => $values) {
    $totalRating += $values['rating'];
    $totalItems++;
}

$totalRating 将保存所有评级的总和,而 $totalItems 将包含项目总数。

Just declare two variables and then increment them on each iteration:

<?php
$homepage = file_get_contents('http://graph.facebook.com/215844978437619/reviews');
$parsed = json_decode($homepage,true);

$totalRating = 0;
$totalItems = 0;
foreach ($parsed['data'] as $key => $values) {
    $totalRating += $values['rating'];
    $totalItems++;
}

$totalRating will hold the sum of all rating while $totalItems will contain the total number of items.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文