2014-07-20 125 views
0

我创建操纵CSV文件PHP类的多维数组。 作为班级的一部分,我有一个功能,允许过滤数据showOnlyWhere。但是,我收到331行(foreach声明行)上的此错误Invalid argument supplied for foreach()。我试着添加global $arr;但这没有奏效。我将如何解决它?过滤基于另一个数组

$this -> rows是包含所有CSV数据的多维阵列。

$arr的格式为:

$key=>$val array(
$key = Column Name 
$val = value that column should contain 
) 

下面是showOnlyWhere功能

function showOnlyWhere($arr) 
    { 

       if($this->showOnlyWhere == true){ 
        $rows = $this->filteredRows; 
       } 
       else{ 
        $rows = $this->rows; 
       } 

       $filter = function ($item){ 
         global $arr; // didn't work 
         foreach($arr as $chkCol => $chkVal){ 
          if ($item[$arr[$chkCol]] != $chkVal){ 
           return false; 
           break(3); 
          }      
         } 
         return true; 
        }; 


       $this->filteredRows = array_filter($rows,$filter);     


       $this->showOnlyWhere = true;  
} 

我认为错误可能有一些做的匿名函数 - 但我真的不知道。

+0

IM过滤'$ rows' – jamesmstone

回答

2

而不是使用global $arr可以使$arr提供给匿名函数通过use

$filter = function ($item) use ($arr) { 
    //global $arr; // didn't work 
    foreach($arr as $chkCol => $chkVal){ 
     if ($item[$arr[$chkCol]] != $chkVal){ 
      return false; 
     }      
    } 
    return true; 
}; 

另外,我注意到,您分配$rows = $this->filteredRows;您填充$this->filteredRows之前。我不确定这是故意的吗?

0

格式为您$ ARR是错误的。

这是错误的:

$key=>$val array(
$key = Column Name 
$val = value that column should contain 
) 

不能提供类对象的foreach,它应该是一个有效的数组。

它应该是这样的:

$arr=array(
$key => 'Column Name', 
$val = 'value that column should contain' 
); 

所以首先你的对象转换为有效的数组。

相关问题