【问题标题】:Append array value in every iteration在每次迭代中附加数组值
【发布时间】:2018-02-21 15:45:05
【问题描述】:

我有数据表,我需要在每次迭代中设置标题。数组包含所有标题。

这可以正常工作

 $this->table->set_heading("","$name[0]","$name[1]","$name[2]","$name[3]","$name[4]","$name[5]"); 

但我需要动态设置

$cnt=count(name);
for($i=0;$i<$cnt;$i++)
{
        //$this->table->set_heading($name[$i],);    
}

解决这个问题的任何解决方案

【问题讨论】:

  • 你可以简单地使用$this-&gt;table-&gt;set_heading("", $name));

标签: php arrays codeigniter datatable


【解决方案1】:

set_heading 不接受单独的参数,而是接受数组。因此,您可以将代码更改为

$this->table->set_heading("", $name);

您可以在这里找到更多信息:https://www.codeigniter.com/user_guide/libraries/table.html

【讨论】:

    【解决方案2】:

    如果 $name 是标题字符串数组,例如

    $name = array("first", "last", "address", "phone");
    

    那么你需要做的就是

    $this->table->set_heading($name);
    

    【讨论】:

      【解决方案3】:

      您正在调用的函数接受一个数组,但对于不接受的函数,您可以使用以下技术。

      您可以使用call_user_func_array

      $args = [""];
      $cnt  = count($name);
      for($i = 0; $i < $cnt; ++$i)
        $args[] = $name[$i];
      call_user_func_array([$this->table, 'set_heading'], $args);
      

      如果您不关心索引,循环也可能会更好一些,即:

      $args = [""];
      foreach($name as $arg)
        $args[] = $arg;
      call_user_func_array([$this->table, 'set_heading'], $args);
      

      或者,您可以只复制数组并将第一个参数转移到数组中

      $args = $name;
      array_unshift($args, "");
      call_user_func_array([$this->table, 'set_heading'], $args);
      

      还请注意,用双引号将您的参数括起来(即:"$name[0]")虽然在技术上是正确的并且可以工作,但形式很差并且会降低性能,请直接使用它们而不使用双引号。

      【讨论】:

        猜你喜欢
        • 2023-01-16
        • 2022-06-10
        • 2019-11-29
        • 2010-11-17
        • 2021-05-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多