note 115186 deleted from function.array-merge by salathe
| From: | salathe@php.net | Date: | Mon, 06 Sep 2021 22:46:55 +0000 |
| Subject: | note 115186 deleted from function.array-merge by salathe | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-216905@lists.php.net to get a copy of this message | ||
Note Submitter: php at metehanarslan dot com
----
Sometimes you need to modify an array with another one here is my approach to replace an
array's content recursively with delete opiton. Here i used "::delete::" as reserved
word to delete items.
<?php
$person= array(
"name" => "Metehan",
"surname"=>"Arslan",
"age"=>27,
"mail"=>"hidden",
"favs" => array(
"language"=>"php",
"planet"=>"mercury",
"city"=>"istanbul")
);
$newdata = array(
"age"=>28,
"mail"=>"::delete::",
"favs" => array(
"language"=>"js",
"planet"=>"mercury",
"city"=>"shanghai")
);
print_r(array_overlay($person,$newdata));
// result: Array ( [name] => Metehan [surname] => Arslan [age] => 28 [favs] => Array (
[language] => js [planet] => mercury [city] => shanghai ) )
function array_overlay($a1,$a2)
{
foreach($a1 as $k => $v) {
if ($a2[$k]=="::delete::"){
unset($a1[$k]);
continue;
};
if(!array_key_exists($k,$a2)) continue;
if(is_array($v) && is_array($a2[$k])){
$a1[$k] = array_overlay($v,$a2[$k]);
}else{
$a1[$k] = $a2[$k];
}
}
return $a1;
}
?>