4

I have two arrays, one of which is a "section" of the other. For example:

$array = array('file_name1'=>'date1',
               'file_name2'=>'date2',
               'file_name3'=> array('file_name3.1'=>'date3.1',
                                    'file_name3.2'=>'date3.2'),
               'file_name4'=>'date4');

$array_part = array('file_name3'=>array('file_name3.2'=>'date3.2.2'));

In my script, the first array holds a directory structure with the final values being the last-modified date. When I find a change, I want to apply the date value from the second array into the original array. Both arrays are dynamically created, so I don't know the depth of either array. How can I apply this value to the original array?

Lee Blake
  • 341
  • 1
  • 2
  • 15
  • 2
    have you tried [`array_merge_recursive`](http://php.net/array_merge_recursive) or perhaps more fitting [`array_replace_recursive`](http://php.net/array_replace_recursive)? – hakre Aug 29 '13 at 19:28
  • possible duplicate of [How to merge multidimensional arrays while preserving keys?](http://stackoverflow.com/questions/16793015/how-to-merge-multidimensional-arrays-while-preserving-keys) – hakre Aug 29 '13 at 19:31
  • `array_replace_recursive` looks like it will work... Somehow missed that when perusing the php manual. Thanks. – Lee Blake Aug 29 '13 at 19:38

2 Answers2

1

You are most likely looking for array_replace_recursive:

print_r(
    array_replace_recursive($array, $array_part)
);

Which gives in your case:

Array
(
    [file_name1] => date1
    [file_name2] => date2
    [file_name3] => Array
        (
            [file_name3.1] => date3.1
            [file_name3.2] => date3.2.2
        )

    [file_name4] => date4
)

Example Code (Demo):

<?php
/**
 * Applying a variable level array to an existing array
 *
 * @link http://stackoverflow.com/q/18519457/367456
 */

$array = array('file_name1' => 'date1',
               'file_name2' => 'date2',
               'file_name3' => array('file_name3.1' => 'date3.1',
                                     'file_name3.2' => 'date3.2'),
               'file_name4' => 'date4');

$array_part = array('file_name3' => array('file_name3.2' => 'date3.2.2'));

print_r(
    array_replace_recursive($array, $array_part)
);
hakre
  • 193,403
  • 52
  • 435
  • 836
0

you can use php referneces

a data can be found here: http://php.net/manual/en/language.references.pass.php

<?php
function foo(&$var)
{
    $var++;
}
function &bar()
{
    $a = 5;
    return $a;
}
foo(bar());
?>
sd1sd1
  • 1,028
  • 3
  • 15
  • 28