1

I have a small function below that accepts associative arrays and I'm struggling to find a way to modify it to accept simpler arrays. It would be easy to create a separate function and remove a foreach loop, but I'm trying to see if there is a more efficient way to achieve this. Any insights would be greatly appreciated.

Function:

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;
}

Array Sample 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 ) )

Array Sample 2:

Array ( [list_item] => EnglishSpanishFrenchCatalanJapanese )
4
  • wouldn't this be a better way of implementing templates ? Commented Mar 8, 2012 at 3:34
  • perhaps php.net/manual/en/function.call-user-func-array.php might help Commented Mar 8, 2012 at 3:38
  • 2
    you can use is_array() to determine if you need the second nested loop or not. Commented Mar 8, 2012 at 3:49
  • @tereško Thanks, that's interesting. I'm using a lot of modifiers so I'm not sure if this would work. Commented Mar 8, 2012 at 14:46

1 Answer 1

1

Add an IF before the foreach($job as $key=>$value) to check if the first item is an array or not:

...
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
}
...
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks this is very elegant...had is_array in my head, but hadn't connected the dots.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.