duanfang7757 2013-12-02 15:18
浏览 41
已采纳

对表中的4列数组进行排序,以便按字母顺序在每列中读取

I'm trying to display a list of models in four columns, I'm doing this using codeigniters table library. Currently I'm passing an alphabetised list of models to a view and then using array_chunk to split the array into groups of four and then passing that to the CI table generator. This creates 4 columns which are alphabetical left to right.

<?php 
  // Build an array of models
  $models_array = array();
  foreach($product->compatible_models as $model)
  {
      $models_array[] = $model['brand'] . ' ' . $model['model'];
  }

  // Split the array into chunks of 4
  $data = array_chunk($models_array, 4);

  // Display the data using codeigniters table library
  $tmpl = array ( 'table_open'  => '<table border="0" cellpadding="2" cellspacing="1" width ="100%" class="mytable">' );
  $this->table->set_template($tmpl);
  $this->table->set_heading(NULL);
  echo $this->table->generate($data);
?>

Is there a way I can modify the $models_array so that the elements are sorted in such a way as to be output reading alphabetically top to bottom down each column rather than across? So that:

 a,b,c,d,e,f,g,h,i,j,k
 =
 a | b | c | d
 e | f | g | h
 i | j | k

Becomes:

 a,d,g,j,b,e,h,k,c,f,i
 =
 a | d | g | j
 b | e | h | k
 c | f | i
  • 写回答

1条回答 默认 最新

  • douyue8191 2013-12-02 16:59
    关注

    You could chunk the array yourself:

    $array = range('a', 'k');
    $numberOfColumns = 4;
    $numberOfRows = ceil(sizeof($array) / $numberOfColumns);
    $data = array_fill_keys(range(1, $numberOfRows), array());
    $i = 1;
    foreach ( $array as $k => $v ) {
        $data[$i][] = $v;
        if ( $i == $numberOfRows ) {
            $i = 1;
        } else {
            $i++;
        }
    }
    

    $data is now:

    Array
    (
        [1] => Array
            (
                [0] => a
                [1] => d
                [2] => g
                [3] => j
            )
    
        [2] => Array
            (
                [0] => b
                [1] => e
                [2] => h
                [3] => k
            )
    
        [3] => Array
            (
                [0] => c
                [1] => f
                [2] => i
            )
    
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应