函数文档

_wp_array_set()

💡 云策文档标注

概述

_wp_array_set() 是一个 WordPress 核心函数,用于根据键路径深度设置数组值,类似于 JavaScript 的 lodash.set(),旨在保持客户端与服务器端实现的一致性。

关键要点

  • 函数通过引用修改输入数组,根据路径数组在深度结构中设置指定值。
  • 路径数组中的键可以是字符串、整数或 null,用于描述嵌套路径。
  • 函数包含参数验证,确保输入数组和路径有效,否则静默返回。
  • 主要用于 WordPress 主题 JSON 处理等场景,如 WP_Theme_JSON 类中的多个方法。

代码示例

$input_array = array();
_wp_array_set( $input_array, array( 'a', 'b', 'c' ), 1 );
// $input_array 变为:
// array(
//     'a' => array(
//         'b' => array(
//             'c' => 1,
//         ),
//     ),
// );

注意事项

  • 函数从 WordPress 5.8.0 版本引入,是内部工具函数,开发者应谨慎使用以避免意外副作用。
  • 路径数组为空或包含无效类型时,函数会直接返回而不修改数组。
  • 值参数可选,默认值为 null,允许设置空值或覆盖现有值。

📄 原文内容

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

Description

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

Example usage:

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

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

Parameters

$input_arrayarrayrequired
An array that we want to mutate to include a specific value in a path.
$patharrayrequired
An array of keys describing the path that we want to mutate.
$valuemixedoptional
The value that will be set.

Default:null

Source

function _wp_array_set( &$input_array, $path, $value = null ) {
	// Confirm $input_array is valid.
	if ( ! is_array( $input_array ) ) {
		return;
	}

	// Confirm $path is valid.
	if ( ! is_array( $path ) ) {
		return;
	}

	$path_length = count( $path );

	if ( 0 === $path_length ) {
		return;
	}

	foreach ( $path as $path_element ) {
		if (
			! is_string( $path_element ) && ! is_integer( $path_element ) &&
			! is_null( $path_element )
		) {
			return;
		}
	}

	for ( $i = 0; $i < $path_length - 1; ++$i ) {
		$path_element = $path[ $i ];
		if (
			! array_key_exists( $path_element, $input_array ) ||
			! is_array( $input_array[ $path_element ] )
		) {
			$input_array[ $path_element ] = array();
		}
		$input_array = &$input_array[ $path_element ];
	}

	$input_array[ $path[ $i ] ] = $value;
}

Changelog

Version Description
5.8.0 Introduced.