WP_Theme_JSON::remove_keys_not_in_schema()protected staticWP 5.8.0

Given a tree, removes the keys that are not present in the schema.

It is recursive and modifies the input in-place.

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

Хуков нет.

Возвращает

Массив. The modified $tree.

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

$result = WP_Theme_JSON::remove_keys_not_in_schema( $tree, $schema );
$tree(массив) (обязательный)
Input to process.
$schema(массив) (обязательный)
Schema to adhere to.

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

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

Код WP_Theme_JSON::remove_keys_not_in_schema() WP 6.5.2

protected static function remove_keys_not_in_schema( $tree, $schema ) {
	if ( ! is_array( $tree ) ) {
		return $tree;
	}

	foreach ( $tree as $key => $value ) {
		// Remove keys not in the schema or with null/empty values.
		if ( ! array_key_exists( $key, $schema ) ) {
			unset( $tree[ $key ] );
			continue;
		}

		if ( is_array( $schema[ $key ] ) ) {
			if ( ! is_array( $value ) ) {
				unset( $tree[ $key ] );
			} elseif ( wp_is_numeric_array( $value ) ) {
				// If indexed, process each item in the array.
				foreach ( $value as $item_key => $item_value ) {
					if ( isset( $schema[ $key ][0] ) && is_array( $schema[ $key ][0] ) ) {
						$tree[ $key ][ $item_key ] = self::remove_keys_not_in_schema( $item_value, $schema[ $key ][0] );
					} else {
						// If the schema does not define a further structure, keep the value as is.
						$tree[ $key ][ $item_key ] = $item_value;
					}
				}
			} else {
				// If associative, process as a single object.
				$tree[ $key ] = self::remove_keys_not_in_schema( $value, $schema[ $key ] );

				if ( empty( $tree[ $key ] ) ) {
					unset( $tree[ $key ] );
				}
			}
		}
	}
	return $tree;
}