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( $items, $key, $default_value );
$items(array) (required)
The array to get the value from.
$key(string) (required)
The complete key hierarchy, using '::' as separator.
$default_value(mixed)
The value to return if the key doesn't exist in the array.
Default: null

ArrayUtil::get_nested_value() code WC 9.4.2

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

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

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

	return $value;
}