2014-07-20 126 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' 
); 

所以首先你的對象轉換爲有效的數組。

相關問題