From 54d5cbdce8e9400e8d4b44e4328ce42040e78c13 Mon Sep 17 00:00:00 2001 From: Dmitriy Simushev Date: Mon, 18 Feb 2013 12:32:36 +0000 Subject: [PATCH] Create array_flatten_recursive function --- src/messenger/webim/libs/common/misc.php | 52 +++++++++++++++++++++++- 1 file changed, 51 insertions(+), 1 deletion(-) diff --git a/src/messenger/webim/libs/common/misc.php b/src/messenger/webim/libs/common/misc.php index cb1e2248..d26aa0c1 100644 --- a/src/messenger/webim/libs/common/misc.php +++ b/src/messenger/webim/libs/common/misc.php @@ -53,6 +53,56 @@ function div($a, $b) return ($a - ($a % $b)) / $b; } - +/** + * Flatten array recursively. + * + * For example if input array is: + * + * $input = array( + * 'first' => 1, + * 'second' => array( + * 'f' => 'value', + * 's' => null, + * 't' => array( + * 'one', 'two', 'three' + * ), + * 'f' => 4 + * ), + * 'third' => false, + * ); + * + * the output array will be: + * + * $output = array( + * 'first' => 1, + * 'second.f' => 'value', + * 'second.s' => null, + * 'second.t.0' => 'one', + * 'second.t.1' => 'two', + * 'second.t.2' => 'three' + * 'second.f' => 4, + * 'third' => false + * ); + * + * + * @param array $arr Array to flatten + * @return array + */ +function array_flatten_recursive($arr) { + $result = array(); + foreach($arr as $key => $value) { + if (is_array($value)) { + // Flatten nested arrays + $value = array_flatten_recursive($value); + foreach($value as $inner_key => $inner_value) { + $result[$key.".".$inner_key] = $inner_value; + } + } else { + // Leave scalar values 'as is' + $result[$key] = $value; + } + } + return $result; +} ?> \ No newline at end of file