Php 用数组键连接foreach循环中的字符串
我有一个函数,它接受一个字符串参数作为特定页面部分的名称,它可以是Php 用数组键连接foreach循环中的字符串,php,arrays,string,oop,Php,Arrays,String,Oop,我有一个函数,它接受一个字符串参数作为特定页面部分的名称,它可以是head或body 函数如下所示: private $html = []; public function doStuff($pageSection, array $views) { foreach ($views as $view) { //Do some other stuff with view $this->html[$pageSection] .= $view->r
head
或body
函数如下所示:
private $html = [];
public function doStuff($pageSection, array $views)
{
foreach ($views as $view) {
//Do some other stuff with view
$this->html[$pageSection] .= $view->renderOutput();
}
print_r($this->html);
}
doStuff('body', array(
//Array of views
));
$view
中的renderOutput()
函数返回一个字符串,并且不会抛出任何错误
当尝试将此字符串添加到特定数组键中的$this->html
数组(即$pageSection
)时,出现以下错误:
注意:未定义索引:body in
第35行的C:\file.php
在下一行(print\r($this->html);
,数组中填充了我想添加到正确数组键body
中的所有字符串
函数get的调用方式如下:
private $html = [];
public function doStuff($pageSection, array $views)
{
foreach ($views as $view) {
//Do some other stuff with view
$this->html[$pageSection] .= $view->renderOutput();
}
print_r($this->html);
}
doStuff('body', array(
//Array of views
));
我试图删除concatenate操作符,只更改数组键内的字符串,这引发了相同的错误
这是怎么发生的?因为我已经在$this->html[$pageSection]
部分添加了数组键
另外,如何解决此问题?String
$this->html[$pageSection] .= 'some data';
意味着您将“某些数据”
连接到应该已经存在的值
如果您在$this->html
中没有键'body'
,并且试图连接到它,您将看到此注意事项
您可以尝试以下方法:
foreach ($views as $view) {
//Do some other stuff with view
// init value with empty string.
if (!isset($this->html[$pageSection])) {
$this->html[$pageSection] = '';
}
$this->html[$pageSection] .= $view->renderOutput();
}
串
$this->html[$pageSection] .= 'some data';
意味着您将“某些数据”
连接到应该已经存在的值
如果您在$this->html
中没有键'body'
,并且试图连接到它,您将看到此注意事项
您可以尝试以下方法:
foreach ($views as $view) {
//Do some other stuff with view
// init value with empty string.
if (!isset($this->html[$pageSection])) {
$this->html[$pageSection] = '';
}
$this->html[$pageSection] .= $view->renderOutput();
}
我在这里没有看到任何带有
body
的东西。可能它在renderOutput
?尝试print\r
outpageSection
它说什么?我在这里没有看到任何带有body
的东西。可能它在renderOutput
?尝试print\r
outpageSection
它说什么?我可以建议移动它吗在foreach循环外部进行检查。无需在每次迭代时检查它,因为$pageSection
是常量。这就完成了!谢谢。但是,当您不在循环中并执行类似$array['randKey']=123;
这样的操作时,为什么可能没有错误?因为$array['randKey']=123;
表示创建密钥randKey并为其分配123
。请参阅-没有连接。请检查$array['randKey'].=123;
您将得到一个警告。当我尝试将字符串分配给数组键时,它给出了相同的错误?不,不会。请查看分配=
和串联=
之间的区别。我是否可以建议将该检查移到foreach循环之外。无需在每次迭代时检查它,因为$pageSection
是常量。这就完成了!谢谢。但是,当您不在循环中,执行类似于$array['randKey']=123;
的操作时,为什么可能没有错误?因为$array['randKey']=123;
意味着创建键randKey并为其分配123
。请参阅-没有连接。请检查$array['randKey'].=123;
您将得到一个警告。当我尝试将字符串分配给数组键时,它给出了相同的错误?不,不会。请查看分配=
和串联=
之间的区别。