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

时间:2014-05-13 13:46:34

标签: php session loops foreach

我希望能够显示当前登录的作者的书籍标题。我使用PHP会话

<? 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 个答案:

答案 0 :(得分:0)

你用这个开始第二个foreach:

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

以此结束:

<?php endforeach; ?>

这是不正确的。使用此:

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

另外,为什么你使用<?php?短标签未启用?使用<?编写速度更快,代码更易读。另外,当你想回显一些变量时,使用php标签使用:

<?=$variable;?>

更快,更易读。

更新

试试这个:

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