note 83889 added to function.array-merge
| From: | monkey dot 05 dot 06 at NOSPAMgmail dot com | Date: | Tue, 17 Jun 2008 04:25:52 +0000 |
| Subject: | note 83889 added to function.array-merge | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-140521@lists.php.net to get a copy of this message | ||
I wrote this function to strip one or more arrays to a single one-dimensional array. Keys assigned
to individual values are preserved; keys assigned to arrays are not.
<?php
function array_merge_deep($arr) { // an array-merging function to strip one or more arrays down to
a single one dimension array
$arr = (array)$arr;
$argc = func_num_args();
if ($argc != 1) {
$argv = func_get_args();
for ($i = 1; $i < $argc; $i++) $arr = array_merge($arr, (array)$argv[$i]);
}
$temparr = array();
foreach($arr as $key => $value) {
if (is_array($value)) $temparr = array_merge($temparr, array_merge_deep($value));
else $temparr = array_merge($temparr, array($key => $value));
}
return $temparr;
}
?>
Example:
<?php
$groceries = array("fruits" => array("apples", "bananas",
"cherries", "grapes"), "dry goods" => array("bread",
"flour", "yeast"), "dairy" => "milk");
$groceries = array_merge_deep($groceries);
echo "<pre>"; print_r($groceries); echo "</pre>";
?>
Yields the following:
Array
(
[0] => apples
[1] => bananas
[2] => cherries
[3] => grapes
[4] => bread
[5] => flour
[6] => yeast
[dairy] => milk
)
----
Server IP: 69.147.83.197
Probable Submitter: 99.139.84.133
----
Manual Page -- http://www.php.net/manual/en/function.array-merge.php
Edit -- https://master.php.net/note/edit/83889
Del: integrated -- https://master.php.net/note/delete/83889/integrated
Del: useless -- https://master.php.net/note/delete/83889/useless
Del: bad code -- https://master.php.net/note/delete/83889/bad+code
Del: spam -- https://master.php.net/note/delete/83889/spam
Del: non-english -- https://master.php.net/note/delete/83889/non-english
Del: in docs -- https://master.php.net/note/delete/83889/in+docs
Del: other reasons-- https://master.php.net/note/delete/83889
Reject -- https://master.php.net/note/reject/83889
Search -- https://master.php.net/manage/user-notes.php