WP_List_Util::filter()publicWP 4.7.0

Filters the list, based on a set of key => value arguments.

Retrieves the objects from the list that match the given arguments. Key represents property name, and value represents property value.

If an object has more properties than those specified in arguments, that will not disqualify it. When using the 'AND' operator, any missing properties will disqualify it.

Метод класса: WP_List_Util{}

Хуков нет.

Возвращает

Массив. Array of found values.

Использование

$WP_List_Util = new WP_List_Util();
$WP_List_Util->filter( $args, $operator );
$args(массив)
An array of key => value arguments to match against each object.
По умолчанию: empty array
$operator(строка)
The logical operation to perform. 'AND' means all elements from the array must match. 'OR' means only one element needs to match. 'NOT' means no elements may match.
По умолчанию: 'AND'

Список изменений

С версии 4.7.0 Введена.

Код WP_List_Util::filter() WP 6.4.3

public function filter( $args = array(), $operator = 'AND' ) {
	if ( empty( $args ) ) {
		return $this->output;
	}

	$operator = strtoupper( $operator );

	if ( ! in_array( $operator, array( 'AND', 'OR', 'NOT' ), true ) ) {
		$this->output = array();
		return $this->output;
	}

	$count    = count( $args );
	$filtered = array();

	foreach ( $this->output as $key => $obj ) {
		$matched = 0;

		foreach ( $args as $m_key => $m_value ) {
			if ( is_array( $obj ) ) {
				// Treat object as an array.
				if ( array_key_exists( $m_key, $obj ) && ( $m_value == $obj[ $m_key ] ) ) {
					++$matched;
				}
			} elseif ( is_object( $obj ) ) {
				// Treat object as an object.
				if ( isset( $obj->{$m_key} ) && ( $m_value == $obj->{$m_key} ) ) {
					++$matched;
				}
			}
		}

		if ( ( 'AND' === $operator && $matched === $count )
			|| ( 'OR' === $operator && $matched > 0 )
			|| ( 'NOT' === $operator && 0 === $matched )
		) {
			$filtered[ $key ] = $obj;
		}
	}

	$this->output = $filtered;

	return $this->output;
}