2010-05-15 92 views
0

我想知道如何在數組對象篩選值的對象值...過濾器在陣列

我只是顯示下面是我的對象數組的一個數據

Object ([_fields:private] => Array ([a] => c7b920f57e553df2bb68272f61570210 [index_date] => 2010/05/11 12:00:58 [b] => i am zahir [c] => google.com [d] => 23c4a1f90fb577a006bdef4c718f5cc2)) 

    Object ([_fields:private] => Array ([a] => c7b920f57e553df2bb68272f61570210 [index_date] => 2010/05/11 12:00:58 [b] => i am zahir [c] => yahoo.com [d] => 23c4a1f90fb577a006bdef4c718f5cc2)) 

    Object ([_fields:private] => Array ([a] => c7b920f57e553df2bb68272f61570210 [index_date] => 2010/05/11 12:00:58 [b] => i am beni [c] => google.com [d] => 23c4a1f90fb577a006bdef4c718f5cc2)) 

    . 
    . 
    . 

    Object ([_fields:private] => Array ([a] => c7b920f57e553df2bb68272f61570210 [index_date] => 2010/05/11 12:00:58 [b] => i am sani [c] => yahoo.com [d] => 23c4a1f90fb577a006bdef4c718f5cc2)) 

我有過濾[C]價值... ...

+0

'C'是對象的私有字段。您只能通過對象方法訪問它。 – 2010-05-15 12:44:17

+0

是的,我們可以通過對象方法來訪問這個值。 – 2010-05-15 12:48:47

回答

0

這並不是說我電子書籍,你到處去訪問私有字段(可能除了屬性注入),但你可以這樣做:

class A { 
    private $variab = array(); 
    public function __construct($val) { 
     $this->variab["c"] = $val; 
    } 
} 

$objects = array(); 
$objects[] = new A("value 1"); 
$objects[] = new A("value 2"); 
$objects[] = new A("value 3"); 

var_dump($objects); 

$prop = new ReflectionProperty("A", "variab"); 
$prop->setAccessible(true); 
$objects_filtered = array_filter($objects, 
    function (A $obj) use ($prop) { 
     $propval = $prop->getValue($obj); 
     return $propval["c"] != "value 2"; 
    } 
); 
var_dump($objects_filtered); 
$prop->setAccessible(false); 

這給:

array(3) { 
    [0]=> 
    object(A)#1 (1) { 
    ["variab":"A":private]=> 
    array(1) { 
     ["c"]=> 
     string(7) "value 1" 
    } 
    } 
    [1]=> 
    object(A)#2 (1) { 
    ["variab":"A":private]=> 
    array(1) { 
     ["c"]=> 
     string(7) "value 2" 
    } 
    } 
    [2]=> 
    object(A)#3 (1) { 
    ["variab":"A":private]=> 
    array(1) { 
     ["c"]=> 
     string(7) "value 3" 
    } 
    } 
} 
array(2) { 
    [0]=> 
    object(A)#1 (1) { 
    ["variab":"A":private]=> 
    array(1) { 
     ["c"]=> 
     string(7) "value 1" 
    } 
    } 
    [2]=> 
    object(A)#3 (1) { 
    ["variab":"A":private]=> 
    array(1) { 
     ["c"]=> 
     string(7) "value 3" 
    } 
    } 
} 

編輯:既然你不使用PHP 5.3.x,則應嘗試這個:

function filterFunc (A $obj) { 
    global $prop; 
    $propval = $prop->getValue($obj); 
    return $propval["c"] != "value 2"; 
} 
$objects_filtered = array_filter($objects, "filterFunc"); 
+0

我收到以下錯誤,,, 看到這個 語法錯誤,在/var/www/nginx-default/ex.php意外T_FUNCTION上線24 線24 功能(A $ OBJ )使用($ prop){ – 2010-05-15 13:24:51

+0

您好請解釋爲什麼發生錯誤... – 2010-05-15 13:37:18

+0

您使用PHP <5.3。 – Artefacto 2010-05-15 13:39:35