ArrayObject Filter (PHP)

I have my data in an ArrayObject , just representing an array. I need to filter the data, array_filter() function will work fine. However, it does not work with ArrayObject as an argument. What is the best way to handle this? Is there a standard function that handles filtering for me?

Example:

 $my_data = ArrayObject(array(1,2,3)); $result = array_object_filter($my_data, function($item) { return $item !== 2; }); 

Is there any function array_object_filter ?

+2
php arrayobject array-filter
source share
3 answers

How do you export it to an actual array and then create a new Array object?

 $my_data = new ArrayObject(array(1,2,3)); $result = new ArrayObject( array_filter( (array) $my_data, function($item) { return $item !== 2; }) ); 
+3
source share

How about this:

 $my_data = new ArrayObject(array(1,2,3)); $callback = function($item) { return $item !== 2; }; $result = new ArrayObject; foreach ($my_data as $k => $item) if ($callback($item)) $result[$k] = $item; 

Alternatively, you can define the array_object_filter () function yourself:

 function array_object_filter($array, $callback) { $result = new ArrayObject; foreach ($array as $k => $item) if ($callback($item)) $result[$k] = $item; return $result; } 
0
source share

How about subclassing ArrayObject and adding a new method to it:

 /** * Filters elements using a callback function. * * @param callable $callback The callback function to use * * @return self */ public function filter(/* callable */ $callback = null) { $this->exchangeArray(array_filter($this->getArrayCopy(), $callback)); return $this; } 
0
source share

All Articles