note 51909 added to function.array-merge
| From: | ViniciusCubasBrand at osu1 dot php dot net | Date: | Thu, 14 Apr 2005 16:32:58 +0000 |
| Subject: | note 51909 added to function.array-merge | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-88023@lists.php.net to get a copy of this message | ||
The following function merges two arrays taking as parameter an user-defined comparison function:
<?
function array_merge_custom(&$array1,&$array2,$comparison_func)
{
$ret_arr = array();
foreach ($array1 as $key1 => $element1)
{
$has_equal_in_2 = false;
foreach($array2 as $key2 => $element2)
{
if (call_user_func($comparison_func,$element1,$element2))
{
$has_equal_in_2 = true;
}
}
if (!$has_equal_in_2)
{
$ret_arr[] = $array1[$key1];
}
}
$ret_arr = array_merge($ret_arr,$array2);
return $ret_arr;
}
?>
For instance:
<?
$a = array(
array('index' => 'ball', 'blabla' => 0),
array('index' => 'coconut'),
array('index' => 'cow'),
array('index' => 'son'),
);
$b = array(
array('index' => 'phone'),
array('index' => 'wallet'),
array('index' => 'ball'),
array('index' => 'son', 'kabum'=> 1)
);
$c = array_merge_custom($a,$b,create_function('$a,$b','return
$a[\'index\'] == $b[\'index\'];'));
print_r($c)
?>
Will produce:
Array
(
[0] => Array
(
[index] => coconut
)
[1] => Array
(
[index] => cow
)
[2] => Array
(
[index] => phone
)
[3] => Array
(
[index] => wallet
)
[4] => Array
(
[index] => ball
)
[5] => Array
(
[index] => son
[kabum] => 1
)
)
----
Manual Page -- http://www.php.net/manual/en/function.array-merge.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+51909
Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+51909&report=yes&reason=added+to+the+manual
Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+51909&report=yes&reason=bad+code
Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+51909&report=yes&reason=spam
Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+51909&report=yes&reason=useless
Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+51909&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+51909&report=yes
Search -- http://master.php.net/manage/user-notes.php