0

我在一个文件中同时拥有PHPHTML,遵循以下模式:

-HTML1
-PHP1
-HTML2
<-script>
-PHP2
</script> -
其余 HTML

PHP2部分,我调用PHP1中的一个函数,该函数返回一个数组。我可以获得 的值count($arr),但无法打印数组中的值。当我在浏览器中检查源代码时,它只是显示为一个空字符串。

当我将函数中的语句从PHP1复制到PHP2时,一切正常 - 我可以打印数组的值。

代码如下:

<?
include('pathdata.php');
function getThePath($node1, $node2){ //pass strings

    $n1 = $matchIDtoNum[$node1]; //get int (from pathdata)
    $n2 = $matchIDtoNum[$node2];

    $res = array();
    $res[0] = $n1;
    $res[1] = $n2;

    return $res;

}


$node1='';
$node2='';
if($_GET["node1"]){
    $node1 = $_GET["node1"];
}

if($_GET["node2"]){
    $node2 = $_GET["node2"];
}

if ($node1!='' && $node2!=''){
$arr = getThePath($node1,$node2);
}


?>

<html>
<head><title>Paths</title>    
<script>

function init(){

<?    
echo ("document.getElementById('msg1').innerHTML = 'test';\n");
if($node1!='' && $node2!=''){

    //$n1 = $matchIDtoNum[$node1];
    //$n2 = $matchIDtoNum[$node2];      
    //$res = array();
    //$res[0] = $n1;
    //$res[1] = $n2;    
    //$arr=$res;

    $num = count($arr);
    $str = implode(' ', $arr); 

    echo ("document.getElementById('msg1').innerHTML = '$arr[0]';\n"); //Empty string
    echo ("document.getElementById('msg2').innerHTML = '$str';\n"); //String with one space character
    echo ("document.getElementById('msg3').innerHTML = '$num'+' '+'$node1'+' '+'$node2';\n"); //this always works
}

?>

}

</script>


</head>
<body onload="init()">
<h1>Given two Nodes, return Shortest Path</h1>
<form name="inputform" action="getpath.php" method="get">
<input type="text" name="node1" /> 
<input type="text" name="node2" /> 
<input type="submit" value="Submit" />
<input type="reset" value="Clear" />
<br/>
<p id ="msg1"></p>
<p id ="msg2"></p>
<p id ="msg3"></p>
<br/>
</form>
</body>
</html>

关于我可能出错的地方有什么建议吗?

谢谢!

编辑添加:对我有用的是将全局$matchIDtoNum;放入函数中。IE

function getThePath($node1,$node2){
    global $matchIDtoNum; 
    $n1 = $matchIDtoNum[$nd1];
    //etc
}

这给了我预期的输出。

感谢所有的评论者和回答者!

4

2 回答 2

0

使用 $node1 和 $node2 作为全局变量。像

function getThePath(){ //don't pass strings 
    global $node1, $node2;
    .....
}

//call function as
$arr = getThePath();

现在你会得到你的数组

于 2012-07-25T04:56:10.980 回答
0

嗯..在这一行:

$n1 = $matchIDtoNum[$node1]; //get int (from pathdata)

看来您想从$matchIDtoNum获取数组值。您不能从函数外部获取数组值,除非您将其作为函数调用。例如像这样:

$n1 = getMatchIDtoNum($node1); // get int (from pathdata)

在文件pathdata.php上有这样一行:

function getMatchIDtoNum($arg){
      // Your code here
      return $matchIDtoNum[$arg];
}
于 2012-07-25T05:04:54.347 回答