从Codeigniter中的多维数组中检索数据

时间:2016-02-05 03:29:47

标签: php arrays codeigniter

我无法从数组中获取数据,只是在运行foreach循环时显示列表项的空白列表。

当我打印我的数组时,它输出以下内容:

Array (
 [Description] => Array (
                [0] => sidewindo 
                [1] => sidewindo 
                [2] => sidewindo 
                [3] => testing ) 
 [comments] => Array   (
               [0] => sidewindo 
               [1] => sidewindo 
               [2] => sidewindo 
               [3] => testing ) 
 [Fld_id] => 625 
 [fld_IsPublic] => Array (
              [0] => 1 ) 
 [action] => s 
 [pk_id] => 7 )

到目前为止我的代码

public function save_data($data)
{
  foreach ($data as $row)
  {
    foreach ($row['Description'] as $show)
      {
         echo $show;
      }  
  }

我尝试过以下类型的for循环也可以从数组中检索数据。我试图从数组中检索数据并在数据库中的另一个表中更新它。在将代码传递给视图之前,我已经在我的模型中编写了这段代码。

for($i=0;$i<count($comments);$i++)
   { 
     $this->db->update->update('tblname',array('TK_id'=>$data['pk_id'],'Fld_id'=>$data['Fld_id'],'fld_description'=>$data['Description'],'fld_comments'=>$data['comments'],'fld_IsPublic'=>$data['fld_IsPublic']),array('TK_id'=>$data['pk_id'],'Fld_id'=>$data['Fld_id']));
    }
}

2 个答案:

答案 0 :(得分:3)

首先,您应该知道echo数组会生成Notice ( Array to string conversion ),因此,根据您正在使用的环境,您更愿意使用print_r

在您echo之前回答您的问题,您应该检查它是否是数组

public function save_data($data){
    $update = array(); 
    foreach ($data as $key=>$row){

        if(is_array($row)){
            foreach($row as $key2=>$row2){
                $update[$key2] = $row2;
                //echo $row2 . "<br>"; 
            }

        }else{
           $update[$key] = $row;             
           //echo $row ."<br>";
        }
     }  
  }

现在您可以使用$update更新您的表格,将其包含在save_data()内部功能中,如果需要,请在foreach中加入save_data()。请记住,建议在更新数据时使用where

//$this->db->where('id', $id); 
$this->db->update('tblname', $update); 

希望有所帮助

答案 1 :(得分:0)

更改您的代码
public function save_data($data)
{
  foreach ($data as $row)
  {
    foreach ($row['Description'] as $show)
      {
         echo $show;
      }  
  }

 public function save_data($data)
 {    
    foreach ($data["comments"] as $key=>$row)
    {
        $data_update = array(   
                                'TK_id'             => $data['pk_id'],                                                                 
                                'Fld_id'            => $data['Fld_id'],
                                'fld_description'   => $data['Description'][$key],                      
                                'fld_comments'      => $row,
                                'fld_IsPublic'      => $data['fld_IsPublic'][0]
                            );
        $this->db->update('tblname',$data_update,array('TK_id'=>$data['pk_id'],'Fld_id'=>$data['Fld_id']));
            //but this will update single row again and again
            //my suggetion is use $this->db->insert('tblname',$data_update); instead 
    }
 }

你会没事的