wp_find_hierarchy_loop_tortoise_hare

函数
wp_find_hierarchy_loop_tortoise_hare ( $callback, $start, $override = array(), $callback_args = array(), $_return_loop = false )
Access
Private
参数
  • (callable) $callback Function that accepts ( ID, callback_arg, ... ) and outputs parent_ID.
    Required:
  • (int) $start The ID to start the loop check at.
    Required:
  • (array) $override Optional. An array of ( ID => parent_ID, ... ) to use instead of $callback. Default empty array.
    Required:
    Default: array()
  • (array) $callback_args Optional. Additional arguments to send to $callback. Default empty array.
    Required:
    Default: array()
  • (bool) $_return_loop Optional. Return loop members or just detect presence of loop? Only set to true if you already know the given $start is part of a loop (otherwise the returned array might include branches). Default false.
    Required:
    Default: false
返回值
  • (mixed) Scalar ID of some arbitrary member of the loop, or array of IDs of all members of loop if $_return_loop
定义位置
相关方法
wp_find_hierarchy_loop_wp_ajax_add_hierarchical_termwp_check_post_hierarchy_for_loopswp_check_term_hierarchy_for_loopswp_privacy_exports_dir
引入
3.1.0
弃用
-

wp_find_hierarchy_loop_tortoise_hare: 这是wp_find_hierarchy_loop函数的一个变体,使用龟兔赛跑算法来检测分层数据结构中的循环。这个算法包括以不同的速度在数据结构中移动两个指针,并检查是否有重叠。对于大型数据结构,这个函数比wp_find_hierarchy_loop更有效。

使用"龟兔赛跑"算法来检测循环。

对于该算法的每一步,兔子走两步,乌龟走一步。如果兔子超过了乌龟,就一定有一个循环。

function wp_find_hierarchy_loop_tortoise_hare( $callback, $start, $override = array(), $callback_args = array(), $_return_loop = false ) {
	$tortoise        = $start;
	$hare            = $start;
	$evanescent_hare = $start;
	$return          = array();

	// Set evanescent_hare to one past hare.
	// Increment hare two steps.
	while (
		$tortoise
	&&
		( $evanescent_hare = isset( $override[ $hare ] ) ? $override[ $hare ] : call_user_func_array( $callback, array_merge( array( $hare ), $callback_args ) ) )
	&&
		( $hare = isset( $override[ $evanescent_hare ] ) ? $override[ $evanescent_hare ] : call_user_func_array( $callback, array_merge( array( $evanescent_hare ), $callback_args ) ) )
	) {
		if ( $_return_loop ) {
			$return[ $tortoise ]        = true;
			$return[ $evanescent_hare ] = true;
			$return[ $hare ]            = true;
		}

		// Tortoise got lapped - must be a loop.
		if ( $tortoise == $evanescent_hare || $tortoise == $hare ) {
			return $_return_loop ? $return : $tortoise;
		}

		// Increment tortoise by one step.
		$tortoise = isset( $override[ $tortoise ] ) ? $override[ $tortoise ] : call_user_func_array( $callback, array_merge( array( $tortoise ), $callback_args ) );
	}

	return false;
}

常见问题

FAQs
查看更多 >