我有一个奇怪的问题,其中echo'ing变量正在运行,但$ str。=正在产生奇怪的结果。
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;
这回声1,2,3。
正确输出为1,2,5,6,3,4,使用
时输出foreach ($comments as $info) {
echo $info['id'];
接下来,我尝试用$ 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在函数内部回显会在函数内部产生一个不同的组合,而不是在返回后的外部。
数组
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
(
)
)
)
)
)
答案 0 :(得分:1)
我很确定
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);
}
}
你正在使用递归,但是一旦你实际递归,你就没有对返回数据做任何事情,所以就好像它从未发生过一样。