66
77class ArrayHelper
88{
9+ private const NESTED_KEY_SEPARATOR = '. ' ;
10+
911 /**
1012 * Retrieves the value of an array element or object property with the given key or property name.
1113 * If the key does not exist in the array or object, the default value will be returned instead.
@@ -49,7 +51,7 @@ public static function getValue(array|object $array, string|\Closure $key, mixed
4951 return $ array [$ key ];
5052 }
5153
52- if (($ pos = strrpos ($ key , ' . ' )) !== false ) {
54+ if (($ pos = strrpos ($ key , self :: NESTED_KEY_SEPARATOR )) !== false ) {
5355 $ array = static ::getValue ($ array , substr ($ key , 0 , $ pos ), $ default );
5456 $ key = substr ($ key , $ pos + 1 );
5557 }
@@ -65,6 +67,23 @@ public static function getValue(array|object $array, string|\Closure $key, mixed
6567 return $ default ;
6668 }
6769
70+ public function setValue (array $ array , string $ key , mixed $ value ): array
71+ {
72+ $ result = $ array ;
73+ $ parts = explode (self ::NESTED_KEY_SEPARATOR , $ key );
74+ if (count ($ parts ) > 1 ) {
75+ $ index = array_shift ($ parts );
76+ if (!array_key_exists ($ index , $ result )) {
77+ $ result [$ index ] = [];
78+ }
79+ $ result [$ index ] = $ this ->setValue ($ result [$ index ], implode (self ::NESTED_KEY_SEPARATOR , $ parts ), $ value );
80+ } else {
81+ $ result [$ key ] = $ value ;
82+ }
83+
84+ return $ result ;
85+ }
86+
6887 /**
6988 * Removes an item from an array and returns the value. If the key does not exist in the array, the default value
7089 * will be returned instead.
0 commit comments