开发者

filter by value in object of array

i want to know how to filter the value in object of array...

i just display the below is one data of my object array

  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 ) ) 

i have to filter the [c] value...


Not that I recomment that you go around accessing private fields (except maybe for property injection), but you can do this:

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);

This gives:

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"
    }
  }
}

EDIT: Since you're not using PHP 5.3.x, try this instead:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜