|
|
|
@ -123,7 +123,14 @@ class BaseArrayHelper
|
|
|
|
|
|
|
|
|
|
/** |
|
|
|
|
* Retrieves the value of an array element or object property with the given key or property name. |
|
|
|
|
* If the key does not exist in the array, the default value will be returned instead. |
|
|
|
|
* If the key does not exist in the array or object, the default value will be returned instead. |
|
|
|
|
* |
|
|
|
|
* The key may be specified in a dot format to retrieve the value of a sub-array or the property |
|
|
|
|
* of an embedded object. In particular, if the key is `x.y.z`, then the returned value would |
|
|
|
|
* be `$array['x']['y']['z']` or `$array->x->y->z` (if `$array` is an object). If `$array['x']` |
|
|
|
|
* or `$array->x` is neither an array nor an object, the default value will be returned. |
|
|
|
|
* Note that if the array already has an element `x.y.z`, then its value will be returned |
|
|
|
|
* instead of going through the sub-arrays. |
|
|
|
|
* |
|
|
|
|
* Below are some usage examples, |
|
|
|
|
* |
|
|
|
@ -136,6 +143,8 @@ class BaseArrayHelper
|
|
|
|
|
* $fullName = \yii\helpers\ArrayHelper::getValue($user, function($user, $defaultValue) { |
|
|
|
|
* return $user->firstName . ' ' . $user->lastName; |
|
|
|
|
* }); |
|
|
|
|
* // using dot format to retrieve the property of embedded object |
|
|
|
|
* $street = \yii\helpers\ArrayHelper::getValue($users, 'address.street'); |
|
|
|
|
* ~~~ |
|
|
|
|
* |
|
|
|
|
* @param array|object $array array or object to extract value from |
|
|
|
@ -144,15 +153,29 @@ class BaseArrayHelper
|
|
|
|
|
* `function($array, $defaultValue)`. |
|
|
|
|
* @param mixed $default the default value to be returned if the specified key does not exist |
|
|
|
|
* @return mixed the value of the element if found, default value otherwise |
|
|
|
|
* @throws InvalidParamException if $array is neither an array nor an object. |
|
|
|
|
*/ |
|
|
|
|
public static function getValue($array, $key, $default = null) |
|
|
|
|
{ |
|
|
|
|
if ($key instanceof \Closure) { |
|
|
|
|
return $key($array, $default); |
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
if (is_array($array) && array_key_exists($key, $array)) { |
|
|
|
|
return $array[$key]; |
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
if (($pos = strrpos($key, '.')) !== false) { |
|
|
|
|
$array = static::getValue($array, substr($key, 0, $pos), $default); |
|
|
|
|
$key = substr($key, $pos + 1); |
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
if (is_object($array)) { |
|
|
|
|
return $array->$key; |
|
|
|
|
} elseif (is_array($array)) { |
|
|
|
|
return isset($array[$key]) || array_key_exists($key, $array) ? $array[$key] : $default; |
|
|
|
|
return array_key_exists($key, $array) ? $array[$key] : $default; |
|
|
|
|
} else { |
|
|
|
|
return $array->$key; |
|
|
|
|
return $default; |
|
|
|
|
} |
|
|
|
|
} |
|
|
|
|
|
|
|
|
|