努力理解为什么函数中的foreach循环不会打印出includes数组中的所有值。非常感谢任何帮助。
数组$ this->包括:
Array (
[0] => http://localhost/assets/css/style.css
[1] => http://localhost/assets/css/internal.css
[2] => http://localhost/assets/css/custom-theme/jquery-ui-1.8.17.custom.css
[3] => http://localhost/assets/js/jquery-ui-1.8.16.custom.min.js
)
功能:
public function print_includes()
{
print_r($this->includes);
// Initialize a string that will hold all includes
$final_includes = '';
foreach ($this->includes as $include)
{
// Check if it's a JS or a CSS file
if (preg_match('/js$/', $include))
{
// It's a JS file
$final_includes .= '<script type="text/javascript" src="' . $include . '"></script>';
}
elseif (preg_match('/css$/', $include))
{
// It's a CSS file
$final_includes .= '<link href="' . $include . '" rel="stylesheet" type="text/css" />';
}
return $final_includes;
}
}
使用$ this-&gt; layouts-&gt; print_includes()打印的内容:
<link href="http://localhost/assets/css/style.css" rel="stylesheet" type="text/css" /></head>
答案 0 :(得分:0)
你的return语句在foreach循环中,所以它只连接第一个link元素然后返回字符串作为函数的结果。尝试将其移出循环。
答案 1 :(得分:0)
让你退出foreach循环
foreach ($this->includes as $include)
{
// Check if it's a JS or a CSS file
if (preg_match('/js$/', $include))
{
// It's a JS file
$final_includes .= '';
}
elseif (preg_match('/css$/', $include))
{
// It's a CSS file
$final_includes .= '';
}
}
return $final_includes;
答案 2 :(得分:0)
你正在使用foreach中的返回值,导致它在第一次循环后停止
public function print_includes()
{
print_r($this->includes);
// Initialize a string that will hold all includes
$final_includes = '';
foreach ($this->includes as $include)
{
// Check if it's a JS or a CSS file
if (preg_match('/js$/', $include))
{
// It's a JS file
$final_includes .= '<script type="text/javascript" src="' . $include . '"></script>';
}
elseif (preg_match('/css$/', $include))
{
// It's a CSS file
$final_includes .= '<link href="' . $include . '" rel="stylesheet" type="text/css" />';
}
}
return $final_includes;
}
答案 3 :(得分:0)
我认为您的foreach
循环不正确
foreach($this->includes as $inc) {
return $final_includes; # should not be here.
}