Filter ArrayObject (PHP)

亡梦爱人 提交于 2019-12-12 22:14:54

问题


I have my data in ArrayObject, simply representing an array. I need to filter the data, function array_filter() would work great. However, it does not work with ArrayObject as argument. What's the best way to treat with this? Is there any standard function which 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 array_object_filter function?


回答1:


How about 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; 
    })
);



回答2:


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;

Alternately, you can define an 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;
}



回答3:


How about subclassing the 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;
}


来源:https://stackoverflow.com/questions/11274846/filter-arrayobject-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!