note 71050 added to function.array-merge

From: Date: Thu, 09 Nov 2006 16:55:56 +0000
Subject: note 71050 added to function.array-merge
Groups: php.notes 
Request: Send a blank email to php-notes+get-119563@lists.php.net to get a copy of this message
I noticed the lack of a function that will safely merge two arrays without losing data due to duplicate keys but different values. So I wrote a quicky that would offset duplicate keys and thus preserve their data. of course, this does somewhat mess up association... <?php $array1=array('cats'=>'Murder the beasties!', 'ninjas'=>'Use Ninjas to murder cats!'); $array2=array('cats'=>'Cats are fluffy! Hooray for Cats!', 'ninjas'=>'Ninas are mean cat brutalizers!!!'); $array3=safe_array_merge($array1, $array2); print_r($array3) /* Array { cats => Murder the beasties!, ninjas => Use ninjas to murder cats!, ?> cats_0 => Cats are fluffy! Hooray for Cats!, ninjas_0 => Ninjas are mean cat brutalizers!!! } function safe_array_merge () { $args = func_get_args(); $result=array(); foreach($args as &$array) { foreach($array as $key=>&$value) { if(isset($result[$key])) { $continue=TRUE; $fake_key=0; while($continue==TRUE) { if(!isset($result[$key.'_'.$fake_key])) { $result[$key.'_'.$fake_key]=$value; $continue=FALSE; } $fake_key++; } } else { $result[$key]=$value; } } } return $result; } ?> ---- Server IP: 64.71.164.2 Probable Submitter: 69.41.14.207 ---- Manual Page -- http://www.php.net/manual/en/function.array-merge.php Edit -- https://master.php.net/note/edit/71050 Del: integrated -- https://master.php.net/note/delete/71050/integrated Del: useless -- https://master.php.net/note/delete/71050/useless Del: bad code -- https://master.php.net/note/delete/71050/bad+code Del: spam -- https://master.php.net/note/delete/71050/spam Del: non-english -- https://master.php.net/note/delete/71050/non-english Del: in docs -- https://master.php.net/note/delete/71050/in+docs Del: other reasons-- https://master.php.net/note/delete/71050 Reject -- https://master.php.net/note/reject/71050 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#119563) next »