我在下面有一个小函数接受关联数组,我正在努力找到一种方法来修改它以接受更简单的数组。创建一个单独的函数并删除foreach循环会很容易,但我试图看看是否有更有效的方法来实现这一点。任何见解将不胜感激。
功能:
public function set_content($file, $data, $section_name)
{
$jobs = new Template_Engine();
$jobs->set_file($file);
$jobs_output = '';
static $section_title = 0;
foreach($data as $job)
{
//print_r($job);
foreach($job as $key=>$value)
{
$jobs->set($key,$value);
}
if ($section_title === 0)
{
$jobs->set("section_title",$section_name);
}
else
{
$jobs->clear_set("section_title");
}
++$section_title;
$jobs_output .= $jobs->output();
}
$section_title = 0;
return $jobs_output;
}
数组样本1:
Array ( [0] => Array ( [custom_id] => 78 [name] => Title Goes [description] => Test [resume_id] => 96 [order_id] => 0 [section_id] => 224 [profile_id] => 38 [user_id] => 1 [vanity_name] => Sample of Template 3 [template_id] => 3 [date_add] => 0000-00-00 00:00:00 [date_mod] => 2012-03-04 11:00:05 ) [1] => Array ( [custom_id] => 76 [name] => A Custom Item [description] => A descrition for a custom item goes here. [resume_id] => 96 [order_id] => 1 [section_id] => 224 [profile_id] => 38 [user_id] => 1 [vanity_name] => Sample of Template 3 [template_id] => 3 [date_add] => 0000-00-00 00:00:00 [date_mod] => 2012-03-04 11:00:05 ) )
数组样本2:
Array ( [list_item] => EnglishSpanishFrenchCatalanJapanese )
答案 0 :(得分:1)
在foreach($job as $key=>$value)
之前添加IF,以检查第一项是否为数组:
...
if (is_array($job)) {
foreach($job as $key=>$value)
{
$jobs->set($key,$value);
}
} else {
// treat here the value of the more simpler array;
// in this case, $job would contain EnglishSpanishFrenchCatalanJapanese
}
...