函数文档

_wp_array_get()

💡 云策文档标注

概述

_wp_array_get() 是一个 WordPress 核心函数,用于根据键路径深度访问数组,类似于 JavaScript 的 lodash.get(),旨在保持客户端和服务器端实现的一致性。

关键要点

  • 函数用途:通过路径数组安全地获取嵌套数组中的值,避免直接访问可能导致的错误。
  • 参数说明:接受三个参数:$input_array(源数组)、$path(键路径数组)和可选的 $default_value(默认返回值)。
  • 返回值:返回路径指定的值,如果路径不存在或输入无效,则返回 $default_value(默认为 null)。
  • 兼容性:自 WordPress 5.6.0 版本引入,广泛应用于主题和插件开发中处理数组数据。

代码示例

$input_array = array(
    'a' => array(
        'b' => array(
            'c' => 1,
        ),
    ),
);
_wp_array_get( $input_array, array( 'a', 'b', 'c' ) );

注意事项

  • 路径数组必须为非空数组,否则直接返回默认值。
  • 函数内部使用 isset() 和 array_key_exists() 进行键存在性检查,确保高效和安全。
  • 路径元素可以是字符串、整数或 null,其他类型将导致返回默认值。

📄 原文内容

Accesses an array in depth based on a path of keys.

Description

It is the PHP equivalent of JavaScript’s lodash.get() and mirroring it may help other components retain some symmetry between client and server implementations.

Example usage:

$input_array = array(
    'a' => array(
        'b' => array(
            'c' => 1,
        ),
    ),
);
_wp_array_get( $input_array, array( 'a', 'b', 'c' ) );

Parameters

$input_arrayarrayrequired
An array from which we want to retrieve some information.
$patharrayrequired
An array of keys describing the path with which to retrieve information.
$default_valuemixedoptional
The return value if the path does not exist within the array, or if $input_array or $path are not arrays.

Default:null

Return

mixed The value from the path specified.

Source

function _wp_array_get( $input_array, $path, $default_value = null ) {
	// Confirm $path is valid.
	if ( ! is_array( $path ) || 0 === count( $path ) ) {
		return $default_value;
	}

	foreach ( $path as $path_element ) {
		if ( ! is_array( $input_array ) ) {
			return $default_value;
		}

		if ( is_string( $path_element )
			|| is_integer( $path_element )
			|| null === $path_element
		) {
			/*
			 * Check if the path element exists in the input array.
			 * We check with `isset()` first, as it is a lot faster
			 * than `array_key_exists()`.
			 */
			if ( isset( $path_element, $input_array[ $path_element ] ) ) {
				$input_array = $input_array[ $path_element ];
				continue;
			}

			/*
			 * If `isset()` returns false, we check with `array_key_exists()`,
			 * which also checks for `null` values.
			 */
			if ( isset( $path_element ) && array_key_exists( $path_element, $input_array ) ) {
				$input_array = $input_array[ $path_element ];
				continue;
			}
		}

		return $default_value;
	}

	return $input_array;
}

Changelog

Version Description
5.6.0 Introduced.