php - Applying a variable level array to an existing array

741

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?

810

Answer

Solution:

You are most likely looking for :

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)
);
512

Answer

Solution:

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());
?>

People are also looking for solutions to the problem: Understanding operator precedence in php

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.