我需要输出所有书架上的所有书籍。此代码仅显示最后一摞书。任何帮助都会有所帮助。
function index()
{
$data['books'] = $this->_books();
$this->load->view('books_view', $data);
}
function _books() {
$xml = simplexml_load_file('books.xml');
foreach ($xml->shelfs as $shelf)
{
$result = '<optgroup label="'.$shelf['id'].'">';
foreach ($shelf->books as $book)
{
$result .= '<option value="'.$book->title.'">'.$book->title.'</option>';
}
$result .= '</optgroup>';
}
return $result;
}
echo form_open('books#');
echo '<select name="books[]" multiple="multiple" onClick="this.form.submit()">';
echo $options;
echo '</select></form>';
只有“Z”的最后一个架子。
<?xml version="1.0" encoding="UTF-8" ?>
<library>
<shelfs id="A">
<strip>
<title>Book Title #1 for A</title>
<author>Author Name #1 for A</author>
</strip>
<strip>
<title>Book Title #2 for A</title>
<author>Author Name #2 for A</author>
</strip>
</comics>
...
<shelfs id="Z">
<strip>
<title>Book Title #1 for Z</title>
<author>Author Name #1 for Z</author>
</strip>
<strip>
<title>Book Title #2 for Z</title>
<author>Author Name #2 for Z</author>
</strip>
</comics>
</library>
答案 0 :(得分:3)
您正在覆盖$result
它应该是.=
并在foreach
开始之前定义
function _books() {
$xml = simplexml_load_file('books.xml');
$result='';
foreach ($xml->shelfs as $shelf)
{
$result.= '<optgroup label="'.$shelf['id'].'">';
foreach ($shelf->books as $book)
{
$result .= '<option value="'.$book->title.'">'.$book->title.'</option>';
}
$result .= '</optgroup>';
}
return $result;
}
答案 1 :(得分:2)
问题在于:
$result = '<optgroup label="'.$shelf['id'].'">';
您正在重置每个循环开头的$result
变量。
是的,@Shakti Singh说的是什么!