note 89428 added to function.array-values
| From: | id_ivan at yahoo dot com | Date: | Sat, 07 Mar 2009 15:29:59 +0000 |
| Subject: | note 89428 added to function.array-values | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-151590@lists.php.net to get a copy of this message | ||
I finally found a way to solve my problem with multidimension array and though to share it here.
This function flatten multi dimension (associative/index) array recursively while maintaining the
key with its value. You can see the example for a better explanation.
<?php
/* ---------------------
* @function array_flatten
* @param array
* @since 0.1
* @return array
* @notes flatten associative multi dimension array recursive
* @update 22:02 3/7/2009
* @author Rivanoor Bren <id_ivan(at)yahoo.com>
---------------------- */
function array_flatten($array, $preserve = FALSE, $r = array()){
foreach($array as $key => $value){
if (is_array($value)){
foreach($value as $k => $v){
if (is_array($v)) { $tmp = $v; unset($value[$k]); }
}
if ($preserve) $r[$key] = $value;
else $r[] = $value;
}
}
$r = isset($tmp) ? array_flatten($tmp, $preserve, $r) : $r;
return $r;
}
print_r($tmp);
/* ---
Array
(
[home] => Array
(
[id] => 1
[pid] => 0
[link] => home
[subcat] =>
)
[works] => Array
(
[id] => 2
[pid] => 0
[link] => works
[subcat] => Array
(
[viz] => Array
(
[id] => 4
[pid] => 2
[link] => viz
[subcat] =>
)
[script] => Array
(
[id] => 5
[pid] => 2
[link] => script
[subcat] => Array
(
[arch] => Array
(
[id] => 6
[pid] => 5
[link] => arch
[subcat] =>
)
)
)
)
)
[blog] => Array
(
[id] => 3
[pid] => 0
[link] => blog
[subcat] =>
)
)
--- */
print_r(array_flatten($tmp, 1));
/* ---
Array
(
[home] => Array
(
[id] => 1
[pid] => 0
[link] => home
[subcat] =>
)
[works] => Array
(
[id] => 2
[pid] => 0
[link] => works
)
[blog] => Array
(
[id] => 3
[pid] => 0
[link] => blog
[subcat] =>
)
[viz] => Array
(
[id] => 4
[pid] => 2
[link] => viz
[subcat] =>
)
[script] => Array
(
[id] => 5
[pid] => 2
[link] => script
)
[arch] => Array
(
[id] => 6
[pid] => 5
[link] => arch
[subcat] =>
)
)
--- */
?>
----
Server IP: 66.207.199.35
Probable Submitter: 125.160.109.94
----
Manual Page -- http://www.php.net/manual/en/function.array-values.php
Edit -- https://master.php.net/note/edit/89428
Del: integrated -- https://master.php.net/note/delete/89428/integrated
Del: useless -- https://master.php.net/note/delete/89428/useless
Del: bad code -- https://master.php.net/note/delete/89428/bad+code
Del: spam -- https://master.php.net/note/delete/89428/spam
Del: non-english -- https://master.php.net/note/delete/89428/non-english
Del: in docs -- https://master.php.net/note/delete/89428/in+docs
Del: other reasons-- https://master.php.net/note/delete/89428
Reject -- https://master.php.net/note/reject/89428
Search -- https://master.php.net/manage/user-notes.php