函数文档

rest_validate_array_contains_unique_items()

💡 云策文档标注

概述

rest_validate_array_contains_unique_items() 是一个 WordPress REST API 函数,用于验证数组是否由唯一项组成。它通过遍历数组并检查重复项来返回布尔值。

关键要点

  • 函数接受一个必需参数 $input_array,即要检查的数组。
  • 返回 true 表示数组包含唯一项,false 表示有重复项。
  • 内部使用 rest_stabilize_value() 和 serialize() 来稳定和序列化值以进行准确比较。
  • 该函数自 WordPress 5.5.0 版本引入。

代码示例

function rest_validate_array_contains_unique_items( $input_array ) {
    $seen = array();

    foreach ( $input_array as $item ) {
        $stabilized = rest_stabilize_value( $item );
        $key        = serialize( $stabilized );

        if ( ! isset( $seen[ $key ] ) ) {
            $seen[ $key ] = true;

            continue;
        }

        return false;
    }

    return true;
}

注意事项

  • 该函数依赖于 rest_stabilize_value() 来遵循 JSON Schema 语义稳定值,确保比较的准确性。
  • 常用于 rest_validate_array_value_from_schema() 和 rest_sanitize_value_from_schema() 等函数中,作为数组验证的一部分。

📄 原文内容

Checks if an array is made up of unique items.

Parameters

$input_arrayarrayrequired
The array to check.

Return

bool True if the array contains unique items, false otherwise.

Source

function rest_validate_array_contains_unique_items( $input_array ) {
	$seen = array();

	foreach ( $input_array as $item ) {
		$stabilized = rest_stabilize_value( $item );
		$key        = serialize( $stabilized );

		if ( ! isset( $seen[ $key ] ) ) {
			$seen[ $key ] = true;

			continue;
		}

		return false;
	}

	return true;
}

Changelog

Version Description
5.5.0 Introduced.