开发者

PHP foreach loop help

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']开发者_如何学C 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.


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


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


foreach($content as $key=>$value){
  if($key == "contentTitle"){
    echo "<table>";
  }
  else{
    echo "<tr><td>";
  }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜