- json_decode: documentation ( source)
- print_r: documentation ( source)
- json_encode: documentation ( source)
<?php
function insertNewNodeTest() {
$array = array(
'a' => array(
'a_1' => 'a_1 text',
),
);
$object = json_decode( json_encode( $array ));
//** $object = new ArrayObject( $array, 0, "RecursiveArrayIterator" );
$iterator = new RecursiveIteratorIterator( new RecursiveArrayIterator( $object ), RecursiveIteratorIterator::CHILD_FIRST );
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
foreach( $iterator as $key => $current ) {
// insert a new empty node
if( $key == 'a_1' ) {
$iterator->getInnerIterator()->offsetSet( 'a_2', new stdClass() );
}
// add new leaf into the previously inserted node
if( $key == 'a_2' ) {
$current->ex_empty = 'not empty now';
}
// add another leaf into the previously inserted node
if( $key == 'a_2' ) {
$current->second_leaf = 'leaf with property';
}
// add third leaf WITH ITERATOR(!) instead of using the $current->third_leaf
if( $key == 'a_2' && $iterator->getInnerIterator()->hasChildren() ) {
$iterator->getInnerIterator()->getChildren()->offsetSet( 'third_leaf', 'leaf with iterator');
}
}
print_r($object);
}
insertNewNodeTest();