Automattic\WooCommerce\Utilities

ArrayUtil::get_nested_value()public staticWC 1.0

Get a value from an nested array by specifying the entire key hierarchy with '::' as separator.

E.g. for [ 'foo' => [ 'bar' => [ 'fizz' => 'buzz' ] ] ] the value for key 'foo::bar::fizz' would be 'buzz'.

Method of the class: ArrayUtil{}

No Hooks.

Return

Mixed. The retrieved value, or the supplied default value.

Usage

$result = ArrayUtil::get_nested_value( $array, $key, $default );
$array(array) (required)
The array to get the value from.
$key(string) (required)
The complete key hierarchy, using '::' as separator.
$default(mixed)
The value to return if the key doesn't exist in the array.
Default: null

ArrayUtil::get_nested_value() code WC 8.6.1

public static function get_nested_value( array $array, string $key, $default = null ) {
	$key_stack = explode( '::', $key );
	$subkey    = array_shift( $key_stack );

	if ( isset( $array[ $subkey ] ) ) {
		$value = $array[ $subkey ];

		if ( count( $key_stack ) ) {
			foreach ( $key_stack as $subkey ) {
				if ( is_array( $value ) && isset( $value[ $subkey ] ) ) {
					$value = $value[ $subkey ];
				} else {
					$value = $default;
					break;
				}
			}
		}
	} else {
		$value = $default;
	}

	return $value;
}