函数文档

map_deep()

💡 云策文档标注

概述

map_deep() 是一个 WordPress 核心函数,用于递归地将回调函数应用于数组或对象中的所有非可迭代元素(即非数组和非对象)。它类似于 array_walk_recursive(),但支持对象处理。

关键要点

  • 函数签名:map_deep( $value, $callback ),其中 $value 可以是数组、对象或标量,$callback 是可调用函数。
  • 递归处理:对数组和对象进行深度遍历,仅对非数组和非对象元素应用回调函数。
  • 返回值:返回应用回调后的值,保持原始结构不变。
  • 相关用途:常用于数据清理,如 wp_slash_strings_only()、wp_kses_post_deep() 等函数内部调用。

代码示例

function map_deep( $value, $callback ) {
    if ( is_array( $value ) ) {
        foreach ( $value as $index => $item ) {
            $value[ $index ] = map_deep( $item, $callback );
        }
    } elseif ( is_object( $value ) ) {
        $object_vars = get_object_vars( $value );
        foreach ( $object_vars as $property_name => $property_value ) {
            $value->$property_name = map_deep( $property_value, $callback );
        }
    } else {
        $value = call_user_func( $callback, $value );
    }

    return $value;
}

注意事项

  • 引入版本:WordPress 4.4.0。
  • 用户贡献示例展示了如何使用 map_deep() 结合 sanitize_text_field 清理用户输入,支持多维数组。

📄 原文内容

Maps a function to all non-iterable elements of an array or an object.

Description

This is similar to array_walk_recursive() but acts upon objects too.

Parameters

$valuemixedrequired
The array, object, or scalar.
$callbackcallablerequired
The function to map onto $value.

Return

mixed The value with the callback applied to all non-arrays and non-objects inside it.

Source

function map_deep( $value, $callback ) {
	if ( is_array( $value ) ) {
		foreach ( $value as $index => $item ) {
			$value[ $index ] = map_deep( $item, $callback );
		}
	} elseif ( is_object( $value ) ) {
		$object_vars = get_object_vars( $value );
		foreach ( $object_vars as $property_name => $property_value ) {
			$value->$property_name = map_deep( $property_value, $callback );
		}
	} else {
		$value = call_user_func( $callback, $value );
	}

	return $value;
}

Changelog

Version Description
4.4.0 Introduced.

User Contributed Notes

  1. Skip to note 2 content

    You can use map_deep to easily sanitize user input.

    $values = array( 'a', '<b>Test</b>', '<>c' );
    
    $values = map_deep( $values, 'sanitize_text_field' );
    
    // Output: array(
    //    "a",
    //    "Test",
    //    "c",
    // )

    This works the same for multidimensional arrays.

    $values = array(
      'option_1' => 'value of this option',
      'option_2' => '<b>value of this option</b>'
    );
    
    $values = map_deep( $values, 'sanitize_text_field' );
      
    // Output: array(
    //   "option_1" => "value of this option",
    //   "option_2" => "value of this option",
    // )