无法访问php函数返回的数组值


Cannot access array values returned by php function

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

-HTML1
-PHP1
-HTML2
&lt-脚本>
-PHP2
&lt-/脚本>
-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>

关于我哪里可能出错,有什么建议吗?

谢谢!

编辑为Add:对我有效的是将全局$matchIDtoNum;放入函数中。即

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

这给了我预期的输出。

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

Mmm。。在这条线上:

$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];
}

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

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

现在您将获得阵列