note 71050 deleted from function.array-merge by cmb
| From: | cmb@php.net | Date: | Mon, 19 Nov 2018 17:08:23 +0000 |
| Subject: | note 71050 deleted from function.array-merge by cmb | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-209734@lists.php.net to get a copy of this message | ||
Note Submitter: zspencer at zacharyspencer dot com
----
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;
}
?>