duanfu1873 2014-05-13 13:46
浏览 68

php foreach。 从数组中选择特定值并将其用作显示循环的参数

I want to be able to display titles of the books of the author who is currently logged in. I'm using PHP session

<? foreach ($books as $book ): ?>

<? foreach ($book as $selbook => $author): ?>
    <option value="$selbook>"$author['author'] == $_SESSION["sess_username"] ? ' selected="selected"' : ''?>> $author?></option>

<li class="active"><a href=""><span class="pull-right"><input id="button" type="submit" name="submitr" value="Edit"></span><i class="icon-fire$
<? echo htmlspecialchars($book['Title'], ENT_QUOTES, 'UTF-8'); ?> <strong> - </strong><em>
<? echo htmlspecialchars($book['author'], ENT_QUOTES, 'UTF-8');?></em></a></li>
<? endforeach; ?>
<? endforeach; ?>
  • 写回答

1条回答 默认 最新

  • donglin6109 2014-05-13 14:14
    关注

    You start 2nd foreach with this:

    <?php foreach ($book as $selbook => $author) { ?>
    

    And end with this:

    <?php endforeach; ?>
    

    It is not correct. Use this:

    <?php foreach ($book as $selbook => $author): ?>
        // some code
    <?php endforeach; ?>
    

    Also, why u use <?php? Short tag is not enabled? Use <? it is much faster to write and code is more readable. Also, when you want to echo some variable, using php tag use this:

    <?=$variable;?>
    

    Much faster and more readable too.

    Update

    Try this:

    <? foreach ($books as $book ): ?>
     <? foreach ($book as $selbook => $author): ?>
      <option value="<?=$selbook;?>" <? if($author['author'] == $_SESSION["sess_username"]): ?>selected="selected"<? endif; ?> ><?=$author;?></option>
    
      <li class="active"><a href=""><span class="pull-right"><input id="button" type="submit"  name="submitr" value="Edit"></span><i class="icon-fire$
      <? echo htmlspecialchars($book['Title'], ENT_QUOTES, 'UTF-8'); ?> <strong> - </strong><em>
      <? echo htmlspecialchars($book['author'], ENT_QUOTES, 'UTF-8');?></em></a></li>
     <? endforeach; ?>
    <? endforeach; ?>
    
    评论

报告相同问题?