note 123082 deleted from function.array-merge by cmb
| From: | cmb@php.net | Date: | Mon, 28 Jan 2019 14:27:31 +0000 |
| Subject: | note 123082 deleted from function.array-merge by cmb | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-210125@lists.php.net to get a copy of this message | ||
Note Submitter: elhanafi213 at gmail dot com
----
I was having a little problem in using array_merge in my project because it have a lot of duplicate
key with unique values. So i decided to write this function.
function array_merge_and_rename_keys(){
$args = func_get_args();
$array_keys = $keys_value = array();
foreach($args as $arrays){
if(is_array($arrays)){
if(end($args) == true){
foreach($arrays as $keys => $values){
@$keys_value[$keys] += 1;
if(in_array($keys, $array_keys)){ $merged[$keys . '_' . $keys_value[$keys]] =
$values; }
else{ $merged[$keys] = $values; $array_keys[] = $keys; }
}
}else{
foreach($arrays as $get_arrays){
if(is_array($get_arrays)){
foreach($get_arrays as $keys => $values){
@$keys_value[$keys] += 1;
if(in_array($keys, $array_keys)){ $merged[$keys . '_' . $keys_value[$keys]] =
$values; }
else{ $merged[$keys] = $values; $array_keys[] = $keys; }
}
}else{ return false; }
}
}
}
}
return $merged;
}
$arr = array(array('a' => 'foo', 'b' => 'bar'),
array('a' => 'foo2', 'b' => 'bar2'),
array('a' => 'foo3', 'b' => 'bar3'),
array('c' => 'foo', 'd' => 'bar'), array('c'
=> 'foo2', 'd' => 'bar2'));
print_r(array_merge($arr[0], $arr[1], $arr[2], $arr[3], $arr[4]));
print_r(array_merge_and_rename_keys($arr[0], $arr[1], $arr[2], $arr[3], $arr[4]));
// or you can use it like this array_merge_and_rename_keys($arr, false) give last argument as false
for two-dimensional arrays
The output is
Array
(
[a] => asd3
[b] => hi3
[c] => asd2
[d] => hi2
)
Array
(
[a] => asd
[b] => hi
[a_2] => asd2
[b_2] => hi2
[a_3] => asd3
[b_3] => hi3
[c] => asd
[d] => hi
[c_2] => asd2
[d_2] => hi2
)
Thanks, All love and respect.
Mohammed.