PHP将两个渲染数组包装在不同的div中

时间:2016-08-08 00:43:45

标签: php foreach

我需要将我的数组包装在foreach循环之外的自己的包装div中。

function foo() {
 //my foreach loops

 $top_content[] = $top;
 $bottom_content[] = $bottom;

 return array($top_content, $bottom_content);
}

理想情况下,我可以:

function foo() {
 //my foreach loops

 $top_content[] = '<div class="wrapper-one">' . $top . '</div>';
 $bottom_content[] = '<div class="wrapper-two">' . $bottom  . '</div>';

 return array($top_content, $bottom_content);
}

但后来我得到一个错误:注意:数组到字符串转换

任何帮助表示感谢。

2 个答案:

答案 0 :(得分:1)

function foo() {
 //my foreach loops

 $top_content[0] = '<div class="wrapper-one">' . $top . '</div>';
 $bottom_content[0] = '<div class="wrapper-two">' . $bottom  . '</div>';

 return array($top_content, $bottom_content);
}

答案 1 :(得分:0)

这是因为您尝试使用字符串连接数组。由于$top$bottom之前可能已初始化为数组。

$top_content[0] = '<div class="wrapper-one">' . $top . '</div>';
$bottom_content[] = '<div class="wrapper-two">' . $bottom  . '</div>';

所以我的猜测是你必须创建$top$bottom作为数组并尝试在for-each循环结束时连接。

你仍然可以这样做。

$topContents    = implode('', $top);
$bottomContents = implode('', $bottom);

$top_content[0] = '<div class="wrapper-one">' . $topContents . '</div>';
$bottom_content[] = '<div class="wrapper-two">' . $bottom  . '</div>';

诀窍是使用php的implode函数首先连接数组。连接后它返回字符串。然后,该字符串可以进一步与其他字符串连接。

尝试一下,让我们知道。

相关问题