Last active
August 29, 2015 14:06
-
-
Save absent1706/d0e3d040855fd387ffd1 to your computer and use it in GitHub Desktop.
Read and write to property of multidimensional array (property is string var)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function getArrayElement($array, $path, $pathDelimiter = '->') | |
{ | |
// searching for element | |
$current_array = &$array; | |
$keys = explode($pathDelimiter, $path); | |
foreach ($keys as $key) | |
{ | |
$current_array = &$current_array[$key]; | |
} | |
return $current_array; | |
} | |
function setArrayElement(&$array, $path, $value, $pathDelimiter = '->') | |
{ | |
// searching for element | |
$current_array = &$array; | |
$keys = explode($pathDelimiter, $path); | |
foreach ($keys as $key) | |
{ | |
$current_array = &$current_array[$key]; | |
} | |
$current_array = $value; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This 2 functions can get ot set array element by path.
Usage example:
array( 'b' => 'val1', 'c' => 'val2' ), 'd' => array( 'e' => 'val3', 'f' => 'val4' ) ); print_r($test_arr); echo "\n"; print_r(getArrayElement($test_arr,'a->b')); echo "\n"; setArrayElement($test_arr,'a->c', 'ololo'); setArrayElement($test_arr,'b', array('1'=>2)); print_r($test_arr);