我正在寻找一种从数组中提取/获取值的方法,并将值分配给变量并获取所有值的总和。
更具体地说,用户将输入一组特定的字母。如果匹配或不匹配,将输入的字母将与现有数组的键进行比较。当数组中存在匹配时,键的相应值(具有匹配项)将被分配给新变量,并且将计算值的总和(w / c预期为数字)。我一直试图找到一种方法,但由于经验不足,我还没有找到一个好方法。
你们有什么想法吗?建议好吗?
以下是代码:
<?php
class GreekNum
{
public function setText($text)
{
$this->text=$text;
}
public function getText()
{
return $this->text;
}
public function Convert($text)
{
$TextLength = strlen($text);
$text = strtoupper($text);
$text = str_split($text);
$collection = array(
"A" => 1,
"B" => 2,
"G" => 3,
"D" => 4,
"E" => 5,
"#" => 6,
"Z" => 7,
"Y" => 8,
"H" => 9,
"I" => 10,
"K" => 20,
"4" => 30,
"M" => 40,
"N" => 50,
"X" => 60,
"O" => 70,
"P" => 80,
"Q" => 90,
"R" => 100,
"S" => 200,
"T" => 300,
"U" => 400,
"F" => 500,
"C" => 600,
"$" => 700,
"W" => 800,
"3" => 900,
);
if(isset($text))
{
$total = 0;
for($i=0; $i<$TextLength; $i++)
{
if(array_key_exists($text[$i], $collection))
{
$total += $text[$i];
}
}
return $total;
}
}
}
$GreekNum = new GreekNum();
$text = $_POST['text'];
$GreekNum->setText($text);
echo "<br>";
echo "<b>Entered Values: </b><br>". $GreekNum->getText();
echo "<br>";
echo "<br>";
echo "<b>Decimal Number Equivalence: </b><br/>". $GreekNum->Convert($text);
?>
对于那些看过这些代码的人,是的,我发布了它,因为有一个我似乎无法找到的错误。我能够修复错误,但现在的问题是我无法真正得到我需要的输出。请理解。感谢。
答案 0 :(得分:1)
如果您想要获得输入的每个字母的值的总和,请将其替换为:
$total += $text[$i];
由此:
$total += $collection[$text[$i]];