PHP array_sum是多维的

时间:2014-09-20 18:55:05

标签: php arrays sum

我需要获得$ product [' stars']的array_sum;所以我可以用它来找到平均值。当我尝试使用它时,我不是以某种方式在阵列上使用它?另外我相信这是一个字符串。是否需要转换为INT?非常感谢任何想法。

<?php

$categories = array();
while ($row_rsCategories = mysqli_fetch_assoc($res)) { 

    $product_array = array();
    $product_array_query = mysqli_query($mysqli,"SELECT id, user_id, client_id, comments, stars FROM reviews WHERE user_id = '".$row_rsCategories['userId']."'");

    while($product_array_fetch = mysqli_fetch_array($product_array_query)) {

       $product_array[] = array("id"=>$product_array_fetch['user_id'],"comments"=>$product_array_fetch['comments'],"stars"=>$product_array_fetch['stars']);

    }                


    $categories[] = array(
        'id' => $row_rsCategories['userId'],
        'name' => $row_rsCategories['usersName'],
        'products' => $product_array,
    );
}

        foreach ($categories as $category) {


?>                  


<div class="col-md-4">
                        <div id = "user-square">  
                                <div class="avatar">
                                    <img src="<?php echo $avatarDir.$list['usersAvatar']; ?>" class="publicAvatar" />
                                </div>

                                <?php    

                                echo $category['name']; ?> </br>

                                <?php foreach($category['products'] as $product) {
                                    echo $product['stars']; ?> </br>
                                <?php   }

?>  

1 个答案:

答案 0 :(得分:2)

您可以将array_sumarray_map

合并来实现
$starsum = array_sum(array_map(function($x) { return $x['stars']; }, $product_array));

但是你也可以在构建结果数组时计算总和:

$starsum = 0;
$rowcount = 0;
while($product_array_fetch = mysqli_fetch_array($product_array_query)) {
    $product_array[] = array("id"=>$product_array_fetch['user_id'],"comments"=>$product_array_fetch['comments'],"stars"=>$product_array_fetch['stars']);
    $starsum += $product_array_fetch['stars'];
    $rowcount++;
}

$categories[] = array(
    'id' => $row_rsCategories['userId'],
    'name' => $row_rsCategories['usersName'],
    'products' => $product_array,
    'avgstars' => ($rowcount == 0) ? 0 : $starsum / $rowcount
);

没有必要将值转换为整数,PHP会在你使用算术函数时自动执行。