php 用栈 做符号匹配 错误 求分析

我想用两个数组实现表达式的四则运算 但是不知道为什么 代码有bug 我分析不出原因
求大神指教

后台代码如下;
传入的是一个用空格分开的算术表达式例如:1 + 2 * 3 + 2


<?php
$result=0; //对result赋值,定义变量。

function youxianji($ch1,$ch2)
{
if($ch2 == '#'||$ch1 == '('||$ch2 == '(')
return 0;
if(($ch1 == '+'||$ch1 == '-')&&($ch2 == '*'||$ch2 == '/'))
return 1;
if(($ch1 == '*'||$ch1 == '/')&&($ch2 == '+'||$ch2 == '-'))
return 0;
if(($ch1 == '*'||$ch1 == '/')&&($ch2 == '*'||$ch2 == '/'))
return 1;
if(($ch1 == '+'||$ch1 == '-')&&($ch2 == '+'||$ch2 == '-'))
return 1;
if($ch1 == ')')
return 1;

}

function operator($d1,$d2,$ch)

{
switch ($ch)
{
case '+':return $d1+$d2;
break;
case '-':return $d1-$d2;
break;
case '*':return $d1*$d2;
break;
case '/':return $d1/$d2;
break;
default :return 0;
}

}

function calu($ch)
{

$a1=array();//存储的运算符的数组
$a2=array();//存储数字的数组
array_push($a1,'#');
$i=0;

while($i<count($ch))
{
if(is_string($it)) //is a char
{
$top=end($a1);//提取运算符
$Doit = youxianji($it,$top); //对运算符或数字进行处理
switch ($Doit)
{
case 0: array_push($a1,$it); //新加进来的优先级高,进栈
break;
// case 0: char_stack.Push((*it)); //新加进来的优先级,进栈
// break;
case 1: $dTemp = end($a2); //加进来的优先级低,相等,需要先运算,此时可能是数字
array_pop($a2);
$dResult = operator(end($a2),$dTemp,end($a1));
array_pop($a2); //出栈后重新赋值入栈
array_push($a2,$dResult);
array_pop($a1); //运算符出栈
if($it != ')')
{
array_push($a1,$it);
}
break;
}
if(($it== ')')&&(end($a1) !='('))
{
//nothing to do
}
else
{
if(($it == ')')&&(end($a1) == '('))
{
array_pop($a1);
}
$i++;
}
}
else if(is_double($it))
{
array_push($a2,$it);
$i++;

}
$it=$ch[$i];

}

while(end($a1) != '#') //所有字符都处理完,留下栈内的字符处理
{
$dTemp = end($a2); //加进来的优先级低,相等,需要先运算
array_pop($a2);
$dResult = operator(end($a2),$dTemp,end($a1));//实行运算
array_pop($a2); //出栈后重新赋值入栈
array_push($a2,$dResult);
array_pop($a1); //运算符出栈
}
return end($a2);
}

if($_POST['suanshi']!=null){
$suanshi=$_POST['suanshi'];
$array=explode(' ',$suanshi);

echo calu($array);

}

else echo "还没输入";

?>

http://bardo.iteye.com/blog/845630

http://wenku.it168.com/d_001271502.shtml