note 116043 added to function.array-merge
| From: | josoort at home dot nl | Date: | Sat, 01 Nov 2014 18:42:31 +0000 |
| Subject: | note 116043 added to function.array-merge | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-200766@lists.php.net to get a copy of this message | ||
This is my personal array combine function which is called "array_new_keys". This name is
based on what it typically does which is creating new keys for a existing array.
My function supports the possibility to have multiple times the same key. It also supports the
possibility to have less keys than values and opposite.
When having multiple times the same key it creates an array on this key for storing all given values
for this key.
When having less keys than values it takes the last given key to store the rest of the values in.
When having less values than keys it takes the last given value the fill the rest of the keys with.
function array_new_keys($pk = array(), $pv = array()) {
if (is_array($pk) && count($pk) > 0) {
$pk = array_values($pk);
} elseif (!is_array($pk)) {
$pk = array($pk);
}
if (is_array($pv) && count($pv) > 0) {
$pv = array_values($pv);
} elseif (!is_array($pv)) {
$pv = array_fill(0, count($pk), $pv);
}
if (count($pv) > 0 && count($pk) > 0 && count($pv) > count($pk)) {
$pk = array_merge($pk, array_fill(0, count($pv) - count($pk), end($pk)));
}
$ar = array();
foreach ($pk as $kk => $kv) {
if (is_array($pv)) {
if (isset($pv[$kk])) {
$nv = $pv[$kk];
} else {
$nv = end($pv);
}
} else {
$nv = $pv;
}
if (isset($ar[$kv])) {
if (!is_array($ar[$kv])) {
$ar[$kv] = array($ar[$kv]);
}
$ar[$kv][] = $nv;
} else {
$ar[$kv] = $nv;
}
}
return $ar;
}
----
Server IP: 91.199.167.223
Probable Submitter: 84.27.186.179
----
Manual Page -- http://php.net/manual/en/function.array-merge.php
Edit -- https://master.php.net/note/edit/116043
Del: integrated -- https://master.php.net/note/delete/116043/integrated
Del: useless -- https://master.php.net/note/delete/116043/useless
Del: bad code -- https://master.php.net/note/delete/116043/bad+code
Del: spam -- https://master.php.net/note/delete/116043/spam
Del: non-english -- https://master.php.net/note/delete/116043/non-english
Del: in docs -- https://master.php.net/note/delete/116043/in+docs
Del: other reasons-- https://master.php.net/note/delete/116043
Reject -- https://master.php.net/note/reject/116043
Search -- https://master.php.net/manage/user-notes.php