-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmatch.php
100 lines (85 loc) · 2.4 KB
/
match.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
<?php
// put full path to Smarty.class.php
require('/usr/local/lib/php/Smarty/libs/Smarty.class.php');
$smarty = new Smarty();
$smarty->setTemplateDir('./smarty/templates');
$smarty->setCompileDir('./smarty/templates_c');
$smarty->setCacheDir('./smarty/cache');
$smarty->setConfigDir('./smarty/configs');
$parties_file = './nazorova_votes.json';
//extract user values
$user = get_user_values();
//read parties
$parties = json_decode(file_get_contents($parties_file));
//calculate match
$results = calc_match($user,$parties);
//create additional link for comparison
$additional_string = create_additional_string($results);
$smarty->assign('query_string', $_SERVER['QUERY_STRING'] . '&' . $additional_string);
$smarty->assign('results', $results);
$smarty->display('match.tpl');
/**
* creates additional string with order of parties
*/
function create_additional_string($results) {
$out = 'order=';
foreach ($results as $row) {
$out .= $row['id'] . '|' . $row['result_percent'] . ',';
}
return rtrim($out,',');
}
/**
* calculates results for one set
*/
function calc_match($user,$set,$extra=2) {
$results = array();
foreach ($set as $s) {
$sum = 0;
$count = 0;
if (count($user['vote']) > 0) {
foreach($user['vote'] as $key => $uv) {
//weight
if (isset($user['weight'][$key])) $w = $extra;
else $w = 1;
//existing divisions only:
if ((property_exists($s,'vote')) and (property_exists($s->vote,$key))) {
$sum = $sum + $w*$s->vote->$key*$uv;
$count = $count + $w;
}
}
}
if ($count == 0) $count = 1; // to allow match = 0/1 = 0;
$results[] = array(
'name' => $s->name,
'short_name' => $s->short_name,
'friendly_name' => $s->friendly_name,
'result' => $sum/$count,
'result_percent' => round(100*$sum/$count),
'id' => $s->id
);
}
//sort by result
foreach ($results as $key => $row) {
$result[$key] = $row['result'];
}
array_multisort($result, SORT_DESC, $results);
return $results;
}
/**
* extracts user's answers
*/
function get_user_values() {
$user = array();
if (count($_GET) > 0) {
foreach ($_GET as $key => $param) {
//votes
if (substr($key,0,2) == 'q-')
$user['vote'][substr($key,2)] = $param;
else if (substr($key,0,2) == 'c-')
$user['weight'][substr($key,2)] = true;
}
} else
return false;
return $user;
}
?>