我已经在这个问题上苦苦挣扎了一段时间了。我无法弄清楚什么是错的。 下面的代码非常简单,VISOR_URL是另一个文件中定义的常量。如果我在forearch循环外回显它会打印常量值。如果我在循环中打印它,它的值会重复。 如果我使用变量,会出现同样的问题。 有任何想法吗?。 提前致谢。 塞巴斯蒂安
<?php
require_once('conf.php');//I require the file where VISOR_URL is defined
//VISOR_URL is defined in conf.php. define('VISOR_URL', $server_ip.'/'.VISOR_NAME);
echo VISOR_URL; //echoes http://192.168.0.15/tncvisornuevo
if (!empty($occurrence_ids)) {//occurrence_ids is an array and values are printed fine
foreach ($occurrence_ids as $key => $value) {
echo VISOR_URL; //echoes http://192.168.0.15/tncvisornuevohttp://192.168.0.15/tncvisornuevo
$ocurrencia = new ca_occurrences($value);
$nombre_ocurrencia = $ocurrencia->get('ca_occurrences.preferred_labels');
$link = '<a href="'.VISOR_URL.'/views/occurrenceDetails.php?occurrence_id='.$value.'">'.$nombre_ocurrencia.'</a>';
echo $link."<br>";
}
}
?>
以下简单示例不会复制常量值:
<?php
//Define a constant
define('CONSTANT', 'imaconstant');
echo CONSTANT."<br>"; //Echoes imaconstant
$test_array = array(0,1,2,3,4,5,6,7,8);
foreach ($test_array as $key => $value) {
echo $value.CONSTANT,"<br>"; //Echoes nimaconstant, n+1imaconstant
}
?>
答案 0 :(得分:1)
循环将会运行多次。例如 -
$array = array('aa','bb','cc');
$var = "abc";
foreach($array as $key => $value);
{
echo $var.'<br>';
}
/*
abc
abc
abc
*/
现在上面因为数组的大小为3,所以循环将运行3次,并回传变量... ofcourse 3次。