tags:

views:

47

answers:

1

hi

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

thanks and advance

A: 

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");
Artefacto
i am getting the following error,,,see this syntax error, unexpected T_FUNCTION in /var/www/nginx-default/ex.php on line 24the line 24 is function (A $obj) use ($prop) {
zahir hussain
hi please explain why that error occured...
zahir hussain
you are using PHP < 5.3.
Artefacto
I've edited the post to be PHP 5.2 compatible.
Artefacto