PHP-返回产生奇怪结果的变量
我遇到了一个奇怪的问题,即echo'ing变量正在工作,而$str.=正在产生奇怪的结果PHP-返回产生奇怪结果的变量,php,arrays,return,Php,Arrays,Return,我遇到了一个奇怪的问题,即echo'ing变量正在工作,而$str.=正在产生奇怪的结果 function displayComments($comments, $str){ foreach ($comments as $info) { $str .= $info['id']; if (!empty($info['childs'])) { $this->displayComments($
function displayComments($comments, $str){
foreach ($comments as $info) {
$str .= $info['id'];
if (!empty($info['childs'])) {
$this->displayComments($info['childs'],$str);
}
}
return $str;
}
$comments = $this->produceComments($id);
if(!$comments){
$str ='
<tr>
<td>There are no comments for this Project</td>
</tr>';
}else{
$str = $this->displayComments($comments,'');
}
echo $str;
接下来,我尝试使用$str.=构建并响应函数
function displayComments($comments,$str=FALSE){
foreach ($comments as $info) {
$str .= $info['id'];
if (!empty($info['childs'])) {
$this->displayComments($info['childs']);
}
}
echo $str;
return $str;
}
这会产生5,6,4,1,2,3,这是不正常和奇怪的。。当它在函数外回声时,它产生1,2,3
为什么正确地回显$info['id']输出,但将值构建到$str中不起作用,同时返回$str会删除值
还有,为什么在函数内部使用$str进行echo’ing会在函数内部产生不同的组合,而不是在返回后在函数外部产生不同的组合
阵列
Array
(
[1] => Array
(
[0] => 1
[id] => 1
[1] => 1
[project_id] => 1
[2] => 0
[parent] => 0
[3] => First post
[comment] => First post
[4] =>
[user] =>
[5] => 2014-02-01
[date] => 2014-02-01
[childs] => Array
(
)
)
[2] => Array
(
[0] => 2
[id] => 2
[1] => 1
[project_id] => 1
[2] => 0
[parent] => 0
[3] => Second Post
[comment] => Second Post
[4] =>
[user] =>
[5] => 2014-02-01
[date] => 2014-02-01
[childs] => Array
(
[0] => Array
(
[0] => 5
[id] => 5
[1] => 1
[project_id] => 1
[2] => 2
[parent] => 2
[3] => Reply to 2nd post
[comment] => Reply to 2nd post
[4] =>
[user] =>
[5] => 2014-02-05
[date] => 2014-02-05
[childs] => Array
(
)
)
[1] => Array
(
[0] => 6
[id] => 6
[1] => 1
[project_id] => 1
[2] => 2
[parent] => 2
[3] => Reply to 2nd post
[comment] => Reply to 2nd post
[4] =>
[user] =>
[5] => 2014-02-05
[date] => 2014-02-05
[childs] => Array
(
)
)
)
)
[3] => Array
(
[0] => 3
[id] => 3
[1] => 1
[project_id] => 1
[2] => 0
[parent] => 0
[3] => Reply to first post
[comment] => Reply to first post
[4] =>
[user] =>
[5] => 2014-02-19
[date] => 2014-02-19
[childs] => Array
(
[0] => Array
(
[0] => 4
[id] => 4
[1] => 1
[project_id] => 1
[2] => 3
[parent] => 3
[3] => Reply to first reply
[comment] => Reply to first reply
[4] =>
[user] =>
[5] => 2014-02-05
[date] => 2014-02-05
[childs] => Array
(
)
)
)
)
)
我很肯定
foreach ($comments as $info) {
$str .= $info['id'];
if (!empty($info['childs'])) {
$this->displayComments($info['childs'],$str);
}
}
应该是
foreach ($comments as $info) {
$str .= $info['id'];
if (!empty($info['childs'])) {
$str = $this->displayComments($info['childs'],$str);
}
}
您使用的是递归,但一旦您真正递归,您就不会对返回数据做任何事情,因此它似乎从未发生过。当我看到这一点时,我也是这么想的。如果要构建$str字符串,请在被调用的方法之外定义它,并且只附加到它。在第一个例子中,有一个“$str=”可能导致了这种奇怪的行为。这正是问题所在。非常感谢,戴夫。
foreach ($comments as $info) {
$str .= $info['id'];
if (!empty($info['childs'])) {
$str = $this->displayComments($info['childs'],$str);
}
}