note 81038 added to function.array-merge-recursive

From: Date: Tue, 12 Feb 2008 10:06:38 +0000
Subject: note 81038 added to function.array-merge-recursive
Groups: php.notes 
Request: Send a blank email to php-notes+get-136061@lists.php.net to get a copy of this message
I've tried these array_merge_recursive functions without much success. Maybe it's just me but they don't seem to actually go more than one level deep? As with all things, its usually easier to write your own, which I did and it seems to work just the way I wanted. Anyways, my function hasn't been tested extensively, but it's a simple function, so in hopes that this might be useful to someone else I'm sharing. Also, the PHP function array_merge_recursive() didn't work for my purposes because it didn't overwrite the values like I needed it to. You know how it works, it just turns it into an array with multiple values... not helpful if your code is expecting one string. function array_merge_recursive_unique($array1, $array2) { // STRATEGY /* Merge array1 and array2, overwriting 1st array values with 2nd array values where they overlap. Use array1 as the base array and then add in values from array2 as they exist. Walk through each value in array2 and see if a value corresponds in array1. If it does, overwrite with second array value. If it's an array, recursively execute this function and return the value. If it's a string, overwrite the value from array1 with the value from array2. If a value exists in array2 that is not found in array1, add it to array1. */ // LOOP THROUGH $array2 foreach($array2 AS $k => $v) { // CHECK IF VALUE EXISTS IN $array1 if(!empty($array1[$k])) { // IF VALUE EXISTS CHECK IF IT'S AN ARRAY OR A STRING if(!is_array($array2[$k])) { // OVERWRITE IF IT'S A STRING $array1[$k]=$array2[$k]; } else { // RECURSE IF IT'S AN ARRAY $array1[$k] = array_merge_recursive_unique($array1[$k], $array2[$k]); } } else { // IF VALUE DOESN'T EXIST IN $array1 USE $array2 VALUE $array1[$k]=$v; } } unset($k, $v); return $array1; } ---- Server IP: 212.199.163.191 Probable Submitter: 79.178.247.112 ---- Manual Page -- http://www.php.net/manual/en/function.array-merge-recursive.php Edit -- https://master.php.net/note/edit/81038 Del: integrated -- https://master.php.net/note/delete/81038/integrated Del: useless -- https://master.php.net/note/delete/81038/useless Del: bad code -- https://master.php.net/note/delete/81038/bad+code Del: spam -- https://master.php.net/note/delete/81038/spam Del: non-english -- https://master.php.net/note/delete/81038/non-english Del: in docs -- https://master.php.net/note/delete/81038/in+docs Del: other reasons-- https://master.php.net/note/delete/81038 Reject -- https://master.php.net/note/reject/81038 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#136061) next »