Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/codeigniter/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 使用Codeigniter实现字母列表_Php_Codeigniter - Fatal编程技术网

Php 使用Codeigniter实现字母列表

Php 使用Codeigniter实现字母列表,php,codeigniter,Php,Codeigniter,我到处寻找这个问题的答案,唉,它像舞会之夜的辣妹一样避开了我 我基本上是在构建一个我的客户请求的目录,该目录要求按字母顺序排列的标题后跟类别名称。这里有一个小转折,我使用的是codeigniter 我有一个基本的模型函数,可以按名称获取所有主要类别 function getAllMainCats(){ $this->db->from('main_categories'); $this->db->order_by('name', 'ASC'); $que

我到处寻找这个问题的答案,唉,它像舞会之夜的辣妹一样避开了我

我基本上是在构建一个我的客户请求的目录,该目录要求按字母顺序排列的标题后跟类别名称。这里有一个小转折,我使用的是codeigniter

我有一个基本的模型函数,可以按名称获取所有主要类别

function getAllMainCats(){
   $this->db->from('main_categories');
   $this->db->order_by('name', 'ASC');

   $query = $this->db->get();
   return $query->result_array();
}
这就是我陷入困境的地方。 我在网上看到了一些不同的结果,但我还没能成功地将它们修改为使用Codeigniter

对于伪代码,这就是我想象的工作方式

getAllMainCategories
foreach( mainCategories as mainCategory){
   grabfirstletterofeachcategory;
   putThatIntoArray();
   Count amount of items in new array
   display that amount of lists
   apply links according to the foreach loop as maincategory.

}
本质上

<li>
   <h3>A</h3>
   <a href='/'>Almond</a>
   <a href='/'>Apple</a>
   <a href='/'>Artichoke</a>
</li>

<li>
   <h3>B</h3>
   <a href='/'>Bacon</a>
   <a href='/'>Banana</a>
   <a href='/'>Beans</a>
</li>
  • A.
  • B

  • ETC实际上离你的伪代码不远:

    $categories = $this->mymodel->getAllMainCats();
    $ordered = array();
    foreach($categories as $cat){
     $first = strtoupper($cat[0]);
     $ordered[$first][] = $cat;
    }
    
    您应该有如下数组:

    array( A => array(  0 => Almond, 1 => Apple..),
           B => array(  0 => Banana...),
    
    现在你可以循环一下:

    <ul>
    <?php foreach($ordered as $key => $value): ?>
    <?php // outer loop over the keys, i.e. the letters: ?>
     <li>
       <h3><?php echo $key;?></h3>
       <ul>
       <?php foreach($value as $val):?>
       <?php // inner loop over the values, i.e. the elements:?>
        <li><a href='/'><?php echo $val;?></a></li>
       <?php endforeach;?>
      </ul>
     </li>
    <?php endforeach;?>
    </ul>
    

    你可以在行动中看到它

    谢谢!实际上,从长远来看,我自己也设法解决了这个问题,但这基本上就是我最终的结果。谢谢你巩固了我的答案,至少我知道我没有以一种非正统的方式实现目标。我不是说这是最正统的方式。它确实做了它需要做的事情,但是可能有更好的操作,比如在数据库中保存第一个字母以便进行更好的查询,或者缓存和分页结果,等等……但这取决于您的设计和应用程序的整体结构。第一步总是让它工作,接下来是优化