【问题标题】:How would I return full output from function in CodeIgniter?如何从 CodeIgniter 中的函数返回完整输出?
【发布时间】:2011-04-08 12:01:07
【问题描述】:

我需要输出所有书架上的所有书籍。下面的代码只输出最后一本书。任何帮助都会有所帮助。

我的控制器:

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 数据:

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

【问题讨论】:

    标签: php xml codeigniter


    【解决方案1】:

    您正在覆盖 $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;
    }
    

    【讨论】:

    • 天哪。谢了哥们。我已经锤了一个小时左右,没有任何运气,哈哈,这对我很有用。我可以相信它如此简单哇。非常感谢。
    • @EMC 你应该肯定接受这个答案!请在到期时给予信用,并让其他人知道这已解决,阅读常见问题解答和指南等等等等......
    • 我做了伙计们 :) 我不能再点击箭头了。我看到绿色箭头,这意味着接受。
    • @EMC:这很好并且被接受了。无需做任何事情。答案已被您接受。谢谢
    【解决方案2】:

    问题出在这里:

    $result = '<optgroup label="'.$shelf['id'].'">';
    

    您将在每个循环开始时重置 $result 变量。

    @Shakti Singh 说的没错!

    【讨论】:

    • 谢谢 Madmartigan,我现在明白了 :)
    猜你喜欢
    • 1970-01-01
    • 2014-09-22
    • 2022-10-07
    • 1970-01-01
    • 2019-09-29
    • 2015-09-08
    • 1970-01-01
    • 2016-09-28
    • 1970-01-01
    相关资源
    最近更新 更多