Jump to content

[solved] Count total of field values from pages in selector


Martinus
 Share

Recommended Posts

 

I retieve my Products by $items as $item.
Inside each $item-page is a $rating field.

$item1 has $rating value 4
$item2 has $rating value 3
etc.

I need to count the $rating field-value inside each $item-page that match my selector to get the average.
To see how many $item each seller has, I used the code below. But I do not know how to proceed:

<?php 
	$qty = $pages->count("parent=/products/, seller=$item"); 
	echo $qty; 
?>
Link to comment
Share on other sites

Hi, you could use PageSum for simplicity. Just install the module and then for example:

$selector = "parent=/products/, seller=$item"; // your selector
$cnt = $pages->count($selector); // number of pages that match $selector
if(!$cnt) echo 'No rated product found';
$sum = $pages->sum($selector, "rating"); // get sum of all matched products from "rating" field with "PageSum"
$avg = $sum / $cnt; // math
echo "Average rating of {$item->title} product (x$cnt) is ". number_format($avg, 2); // format number as needed

 

  • Like 1
Link to comment
Share on other sites

Oh thanks for that! I prefer not to install to much extra's though.

I also came up with a solution:

<?php 
    $avg = $pages->find("parent=/products/, seller=amazon, rating>0"); 
    $a = array(); 					// create new array
    foreach($avg as $nr) { 			// loop through items from selector
    	$rating = $nr->rating; 		// place the found number in a variable
    	array_push($a, $rating); 	// place the variable in the created array
    } 
    print_r ($a); 					// check array
    echo array_sum($a); 			// sum of all values in array
?>

 

Link to comment
Share on other sites

  • Martinus changed the title to [solved] Count total of field values from pages in selector

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...