BigToach.com

PHP Snippets

rating

Information

(PHP Version >= 4.3.0)
Functions used in this snippet: file_exists, is_readable, is_array, unserialize, file_get_contents, array_key_exists, array_sum, sizeof, array_merge, fopen, fwrite, serialize, fclose.

Description

str rating( str file, str get [, mixed add ] )

Uses file to store ratings for different values. The values are stored by their get key. If the add parameter is set, a new value will be added to get with the value of add.

Snippet

<?php
function rating($file,$get,$add=NULL){
    global 
$_array;
    if(!
file_exists($file) || !is_readable($file)){
        return 
0;
    }
    
$_array is_array($_array) ? $_array unserialize(file_get_contents($file));
    
$_array is_array($_array) ? $_array : array();
    if(
$add === NULL){
        if(
array_key_exists($get$_array)){
             
$rating array_sum($_array[$get]) / sizeof($_array[$get]);
        }else{
            return 
0;
        }
    }else{
        
$add is_array($add) ? $add : array($add);
        
$_array[$get] = array_merge($_array[$get],$add);
        
$rating array_sum($_array[$get]) / sizeof($_array);
        
$fp fopen($file,'w');
        
fwrite($fp,serialize($_array));
        
fclose($fp);
    }
    return 
$rating;
}
?>

Example

rating Can be used in the following way:

<?php
// add a vote of 5 to something with an id of 4
echo rating('file.txt''4''5'); // returns the average (5 if not previously set)

// add another vote
echo rating('file.txt''4''1'); // returns the average (3 using the example from above again (5+1/2))

// get the rating of something
echo rating('file.txt','4');
// returns the rating (using example from above 3 would return again);

echo rating('file.txt''newpost');
// gets the rating for the field stored as newpost
?>

Added on Jul 5th at 6 am by Scott - 0 Comments
Updated on Jul 5th at 6 am.


0 Responses to rating

Name:

Site or Mail:

Comment:

To try to reduce the ammount of spam, please enter the word GOOSE in the following form

Security Code: