Skip to content

Instantly share code, notes, and snippets.

@anver
Last active July 29, 2018 12:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anver/4d1d00766362880bc55696db106b8d4d to your computer and use it in GitHub Desktop.
Save anver/4d1d00766362880bc55696db106b8d4d to your computer and use it in GitHub Desktop.
function test_set_values() {
$data = [
'test' => 'value',
'level_one' => [
'level_two' => [
'level_three' => [
'replace_this_array' => [
'key_one' => 'testing',
'key_two' => 'value',
'special_key' => 'replacement_value',
'four' => 'another value'
]
],
'ordinary_key' => 'value'
]
]
];
$arrObject = json_decode( json_encode( $data ) );
$completeIterator = new RecursiveIteratorIterator( new RecursiveArrayIterator( $arrObject ), RecursiveIteratorIterator::SELF_FIRST );
foreach ( $completeIterator as $key => $value ) {
if ( property_exists( $value, 'special_key' ) ) {
$replaced_array = array_fill( 0, count( ( array ) $value ), $value->special_key );
$combined_array = array_combine( array_keys( ( array ) $value ), array_values( $replaced_array ) );
$combined_array['profession'] = 'Programmer';
$current_depth = $completeIterator->getDepth();
for ( $subDepth = $current_depth; $subDepth >= 0; $subDepth-- ) {
$subIterator = $completeIterator->getSubIterator( $subDepth );
// If we are on the level we want to change, use the replacements ($value)
// other wise set the key to the parent iterators value
if ( $subDepth === $current_depth ) {
$newVal = ( object ) $combined_array;
} else {
$newVal = $completeIterator->getSubIterator( $subDepth + 1 )->getArrayCopy();
}
$subIterator->offsetSet( $subIterator->key(), $newVal );
}
}
}
print_r( $arrObject );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment