Applying an array of variable levels to an existing array

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

$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 contains a directory structure whose final values ​​are the date of the last change. When I find the change, I want to apply the date value from the second array to the original array. Both arrays are dynamically created, so I do not know the depth of any array. How can I apply this value to the original array?

+4
source share
2 answers

You are most likely looking for array_replace_recursive :

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

What 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 ) 

Code Example ( 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) ); 
+1
source

you can use php referneces

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

Source: https://habr.com/ru/post/1499686/


All Articles