note 124151 added to function.array-merge-recursive
| From: | gullevek at gullevek dot org | Date: | Thu, 29 Aug 2019 08:06:45 +0000 |
| Subject: | note 124151 added to function.array-merge-recursive | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-212031@lists.php.net to get a copy of this message | ||
walfs version is pretty good, but it always assumes we want numeric keys as numeric keys. There are
possibilities where a numeric key is actually a string '123'
For that I modified the function so that the last argument is a true switch to turn keys can be
numeric on. Default is that keys are all string.
<?php
function array_merge_recursive_simple()
{
// croak on not enough arguemnts (we need at least two)
if (func_num_args() < 2) {
trigger_error(__FUNCTION__ .' needs two or more array arguments', E_USER_WARNING);
return;
}
// default key is not string
$key_is_string = false;
$arrays = func_get_args();
// if last is not array, then assume it is trigger for key is always string
if (!is_array(end($arrays))) {
if (array_pop($arrays)) {
$key_is_string = true;
}
}
// check that arrays count is at least two, else we don't have enough
if (count($arrays) < 2) {
trigger_error(__FUNCTION__.' needs two or more array arguments', E_USER_WARNING);
return;
}
$merged = array();
while ($arrays) {
$array = array_shift($arrays);
if (!is_array($array)) {
trigger_error(__FUNCTION__ .' encountered a non array argument', E_USER_WARNING);
return;
}
if (!$array) {
continue;
}
foreach ($array as $key => $value) {
if (is_string($key) || $key_is_string === false) {
if (is_array($value) && array_key_exists($key, $merged) &&
is_array($merged[$key])) {
$merged[$key] = call_user_func(__FUNCTION__, $merged[$key], $value, $key_is_string);
} else {
$merged[$key] = $value;
}
} else {
$merged[] = $value;
}
}
}
return $merged;
}
?>
----
Server IP: 208.43.231.9
Probable Submitter: 82.199.157.54 (proxied: 122.212.154.178)
----
Manual Page -- http://php.net/manual/en/function.array-merge-recursive.php
Edit -- https://master.php.net/note/edit/124151
Del: integrated -- https://master.php.net/note/delete/124151/integrated
Del: useless -- https://master.php.net/note/delete/124151/useless
Del: bad code -- https://master.php.net/note/delete/124151/bad+code
Del: spam -- https://master.php.net/note/delete/124151/spam
Del: non-english -- https://master.php.net/note/delete/124151/non-english
Del: in docs -- https://master.php.net/note/delete/124151/in+docs
Del: other reasons-- https://master.php.net/note/delete/124151
Reject -- https://master.php.net/note/reject/124151
Search -- https://master.php.net/manage/user-notes.php