Skip to content

Instantly share code, notes, and snippets.

@neotohin
Last active December 17, 2015 20:49
Show Gist options
  • Save neotohin/5670660 to your computer and use it in GitHub Desktop.
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.
<?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