Last active
December 17, 2015 20:49
-
-
Save neotohin/5670660 to your computer and use it in GitHub Desktop.
Get reference of a specific item via sequence from a multi-dimension array.
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
<?php | |
/** | |
* Sample Array | |
*/ | |
$arr = array( | |
'key_1' => array( | |
'key_1_1' => array( | |
'key_1_1_1' => array( | |
'key_1_1_1_1' => array( | |
'data' | |
) | |
) | |
) | |
), | |
'key_2' => array( | |
'key_2_1' => array( | |
'key_2_1_1' => array( | |
'key_2_1_1_1' => array( | |
'data' | |
) | |
) | |
) | |
) | |
); | |
// A small recursion function to get that reference | |
function &getRef( &$master, $seg, $index) | |
{ | |
if( $index == count($seg) ) { | |
return $master; | |
} | |
if( !isset($master[ $seg[$index]]) ) | |
return false; | |
return getRef( $master[ $seg[$index]], $seg, $index+1); | |
} | |
$item = &getRef( $arr, array('key_1','key_1_1', 'key_1_1_1'), 0); | |
$item2 = &getRef( $arr, array( 'key_2', 'key_2_1'), 0); | |
// Now u can add item | |
$item['new_key'] = 'Hooooray !!'; | |
$item2['another_new_key'] = 'YUP'; | |
print_r( $arr); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment