我在PHP中有一个类结构,我用它来允许对教师标记簿中的平均标记进行不同的计算。我试图让这个尽可能灵活......
每个Assessment
(A)都有一个标记和一个加权来计算整体平均值。该对象具有getMark
和getWeighting
方法,可以提取标记和权重。
扩展Assessment
类以创建可以存储许多评估的WeightedAverage
(W)对象。除了标记(未使用)和权重之外,它还包括一系列评估。重写getMark
方法以使用Assessment
对象数组计算标记(根据所使用的OO的性质,可以包括其他加权平均值)。
最后,Assessment
类被扩展为创建一个TopX
(T)对象,该对象可以存储许多评估并返回存储在其中的顶级“X”评估的平均值。
我现在需要存储教师想要在数据库中使用的“算法”。我设想将其存储为可能如下所示的字符串:
W(A(1,10),A(2,10),A(3,10),T(3,30,A(4,1),A(5,1),A(6,1),A(7,1),W(A(8,1),A(9,1))))
这将根据评估1的加权平均值计算最终结果,调整为10,评估2调整为10,评估3调整为10,然后将前3个评估调整为30个评估4,5,6,7和组合评估平均值为8和9,每个均等加权。
理想情况下,我想得到一个类似于此的数组,然后可以很容易地将其转换为计算所需的对象。
$array [0] ['type'] = 'W'
$array [0] [0] = 'A(1,10)'
$array [0] [1] = 'A(2,10)'
$array [0] [2] = 'A(3,10)'
$array [0] [3] ['type'] = 'T'
$array [0] [3] ['params'] = '3,30'
$array [0] [3] [0] = 'A(4,1)'
$array [0] [3] [1] = 'A(5,1)'
$array [0] [3] [2] = 'A(6,1)'
$array [0] [3] [3] = 'A(7,1)'
$array [0] [3] [4] ['type'] = 'W'
$array [0] [3] [4] [0] = 'A(8,1)'
$array [0] [3] [4] [1] = 'A(9,1)'
我不知道正则表达式是否是前进的方式,或者这是否需要一些大量的编码......
请随时为此问题提出其他解决方案。目前,这仍处于规划阶段!
答案 0 :(得分:1)
您需要一个简单的解析器。但是我会使用正则表达式来更容易地分割标记(否则你会对字符串函数有更多的工作)。
$str = 'W(A(1,10),A(2,10),A(3,10),T(3,30,A(4,1),A(5,1),A(6,1),A(7,1),W(A(8,1),A(9,1))))';
preg_match_all('/[AWT()]|\d+/', $str, $token);
print_r(group($token[0]));
function group(&$t, $type="ROOT") {
$data["type"] = $type;
while ($token = array_shift($t)) {
switch ($token) {
case "A": case "W": case "T":
$type = $token;
break;
case "(":
$d = group($t, $type);
$data[] = $d;
// or $data[] = $type=="A" ? "A(".implode(",",array_slice($d,1)).")" : $d;
break;
case ")":
return $data;
default:
$data[] = $token;
}
}
return $data;
}
它没有给出你想要的结果。它根据简单的规则拆分每个组:
Array
(
[type] => ROOT
[0] => Array
(
[type] => W
[0] => Array
(
[type] => A
[0] => 1
[1] => 10
)
[1] => Array
(
[type] => A
[0] => 2
[1] => 10
)
[2] => Array
(
[type] => A
[0] => 3
[1] => 10
)
[3] => Array
(
[type] => T
[0] => 3
[1] => 30
[2] => Array
(
[type] => A
[0] => 4
[1] => 1
)
[3] => Array
(
[type] => A
[0] => 5
[1] => 1
)
[4] => Array
(
[type] => A
[0] => 6
[1] => 1
)
[5] => Array
(
[type] => A
[0] => 7
[1] => 1
)
[6] => Array
(
[type] => W
[0] => Array
(
[type] => A
[0] => 8
[1] => 1
)
[1] => Array
(
[type] => A
[0] => 9
[1] => 1
)
)
)
)
)
因此您可能实际上必须再次遍历它,并再次将A
组压缩为字符串。但这似乎很容易。
或者看到注释掉的单行代码再次折叠A(x,y)代币:
Array
(
[type] => ROOT
[0] => Array
(
[type] => W
[0] => A(1,10)
[1] => A(2,10)
[2] => A(3,10)
[3] => Array
(
[type] => T
[0] => 3
[1] => 30
[2] => A(4,1)
[3] => A(5,1)
[4] => A(6,1)
[5] => A(7,1)
[6] => Array
(
[type] => W
[0] => A(8,1)
[1] => A(9,1)
)
)
)
)