tags:

views:

175

answers:

3

I am working with a PHP foreach loop and I need it to output some specific HTML depending on which array value it is spitting out.

Everytime that the foreach loop hits a $content['contentTitle'] I need it to insert a new table and then from there carry on. Essentially I want the for the loop to spit out a new table everytime a new contentTitle is found, but then add the rest of the data in the array as tr and td's.

+5  A: 

Well, add an if condition inside of your loop. If it hits a $content['contentTitle'], then close previous table and start a new one.

Col. Shrapnel
A: 
foreach($content as $key=>$value){
  if($key == "contentTitle"){
    echo "<table>";
  }
  else{
    echo "<tr><td>";
  }
}
N 1.1
+1  A: 

Assuming that $content is an element of some parent array, and that the first entry in that parent array does have a contentTitle entry, then you'd do something like this:

$first = true;
echo "<table>\n"; // start initial table
foreach ($stuff as $content) {
    if ($content['contentTitle']) {
        if (!$first) {
           // If this is NOT the $first run through, close the previous table
           $first = false; //... and set the sentinel to false
           echo "</table>\n";
        }
        // output the contentTitle
        echo <<<EOF
<h1>{$content['contentTitle']}</h1>

<table>

EOF;
    } else {
        // otherwise output the regular non-title content
        echo <<<EOF
<tr>
    <td>{$content['this']}</td>
    <td>{$content['that']}</td>
    <td>{$content['somethingelse']}</td>
</tr>

EOF;
   }
}
Marc B